<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.lenovo.service.MainActivity" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="普通方式启动" android:onClick="bt_1"/> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="普通方式停止" android:onClick="bt_2"/>
package com.example.lenovo.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
public MyService() {
Log.e("TAG","MyService被创建");
}
@Override
public void onCreate() {
Log.e("TAG","onCreate被调用");
super.onCreate();
}
@Override
public void onDestroy() {
Log.e("TAG","onDestroy被调用");
super.onDestroy();
}
@Override
public void onRebind(Intent intent) {
Log.e("TAG","onRebind被调用");
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
Log.e("TAG","onUnbind被调用");
return super.onUnbind(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String string = intent.getStringExtra("test");
Log.e("TAG","onStartCommand被调用,并收到数据="+string);
return super.onStartCommand(intent, flags, startId);
}
public class MyBinder extends Binder
{
//定义数据交换的方法
}
//回调方法
//绑定
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG","onBind被调用");
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
return new MyBinder();
}
}
package com.example.lenovo.service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//普通方式启动
public void bt_1(View v)
{
//准备Intent:显式意图
Intent intent = new Intent(this,MyService.class);
intent.putExtra("test","发送的数据");
//启动Service
startService(intent);
Toast.makeText(MainActivity.this, "Service已启动", Toast.LENGTH_SHORT).show();
}
//普通方式关闭
public void bt_2(View v)
{
//准备Intent:显式意图
Intent intent = new Intent(this,MyService.class);
//关闭Service
stopService(intent);
Toast.makeText(MainActivity.this, "Service已停止", Toast.LENGTH_SHORT).show();
}
继承于Service,并在AndroidManifest中注册