服务概述
服务的生命周期

服务的两种启动方式-启动方式(startService)


MainActivity.java
package com.bluelesson.servicedemo;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void btnstart1(View view) {//1.创建IntentIntent intent=new Intent();//2.设置信息intent.setClass(this,MyService.class);// 3.启动服务startService(intent);}public void btnstop1(View view) {//1.创建IntentIntent intent=new Intent();//2.设置信息intent.setClass(this,MyService.class);// 3.关闭服务stopService(intent);}}
MyService.java
package com.bluelesson.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class MyService extends Service {public MyService() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}@Overridepublic void onCreate() {super.onCreate();Log.d("15pb","MyService::onCreate");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d("15pb","MyService::onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {Log.d("15pb","MyService::onDestroy");super.onDestroy();}}
startService方式实例-电话监听器
关键代码
AndroidManifest.xml

activity_main.xml

MainActivity.java
MyService.java
package com.bluelesson.servicedemo;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;import android.util.Log;public class MyService extends Service {public MyService() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}public class MyPhoneListener extends PhoneStateListener{@Overridepublic void onCallStateChanged(int state, String incomingNumber) {super.onCallStateChanged(state, incomingNumber);switch (state){case TelephonyManager.CALL_STATE_IDLE:Log.d("15pb","MyService::电话空闲");break;case TelephonyManager.CALL_STATE_OFFHOOK:Log.d("15pb","MyService::电话接听");break;case TelephonyManager.CALL_STATE_RINGING:Log.d("15pb","MyService::电话响铃");break;}}}private TelephonyManager mTm;private MyPhoneListener mListener;@Overridepublic void onCreate() {super.onCreate();Log.d("15pb","MyService::onCreate");//初始化//1.获取电话管理器mTm=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);//2.创建监听器mListener=new MyPhoneListener();//3.益听mTm.listen(mListener,PhoneStateListener.LISTEN_CALL_STATE);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d("15pb","MyService::onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {Log.d("15pb","MyService::onDestroy");super.onDestroy();//取消监听mTm.listen(mListener,PhoneStateListener.LISTEN_NONE);}}
startService方式实例-计时器

关键代码






activity_main.xml
MainActivity.java

TimerService.java
package com.bluelesson.servicedemo;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;import java.util.Timer;import java.util.TimerTask;public class TimerService extends Service {public TimerService() {}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.throw new UnsupportedOperationException("Not yet implemented");}private Timer mTimer;private int mCount=0;private String mShowText="当前计时:0";@Overridepublic void onCreate() {super.onCreate();//1.创建定时器mTimer=new Timer();//2.创建定时器任务TimerTask timerTask = new TimerTask() {@Overridepublic void run() {Log.d("15pb",mShowText+mCount);//发送广播Intent intent=new Intent();intent.setAction("MyTimer");intent.putExtra("time",mCount);sendBroadcast(intent);mCount++;}};//3.给定时器指定定时器任务mTimer.schedule(timerTask,0,1000);}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {mCount=0;//重置return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();//取消定时器if(mTimer!=null)mTimer.cancel();mTimer=null;}}
服务的两种启动方式-绑定方式(bindService)



绑定方式(bindService)实例-本地人员查询系统
实例
关键代码





main_activity.xml

IPersonListener.java
MyBindService.java
package com.bluelesson.bindservice;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class MyBindService extends Service {public MyBindService() {}String strings[] = {"齐天大圣","猪八戒","沙和尚","白龙马"};public class MyBinder extends Binder implements IPersonListener{@Overridepublic String queryNameById(int id) {if(id<0|| id>3) {return "唐 僧";}return strings[id];}}public MyBinder myBinder;@Overridepublic void onCreate() {super.onCreate();myBinder = new MyBinder();Log.d("15pb","MyBindService::onCreate");}@Overridepublic IBinder onBind(Intent intent) {// TODO: Return the communication channel to the service.Log.d("15pb","MyBindService::onBind");return myBinder;}@Overridepublic boolean onUnbind(Intent intent) {Log.d("15pb","MyBindService::onUnbind");if(myBinder!=null){myBinder=null;}return super.onUnbind(intent);}@Overridepublic void onDestroy() {super.onDestroy();}}
MainActivity.java
package com.bluelesson.bindservice;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.EditText;import android.widget.TextView;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myServiceConnection = new MyServiceConnection();}private MyServiceConnection myServiceConnection;private MyBindService.MyBinder myBinder;public class MyServiceConnection implements ServiceConnection{@Overridepublic void onServiceConnected(ComponentName componentName,IBinder iBinder) {myBinder = (MyBindService.MyBinder)iBinder;}@Overridepublic void onServiceDisconnected(ComponentName componentName) {}}public void btnBind(View view) {Intent intent=new Intent(this, MyBindService.class);bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);}public void btnUnBind(View view) {Intent intent=new Intent(this, MyBindService.class);unbindService(myServiceConnection);stopService(intent);}public void btnQuery(View view) {EditText editText = findViewById(R.id.edit_query);String string = editText.getText().toString();int num = Integer.parseInt(string);if(myBinder!=null) {String name = myBinder.queryNameById(num);TextView textView = findViewById(R.id.tv1);textView.setText(name);}}}
绑定方式(bindService)实例-远程人员查询系统


关键代码
AIDL的app
MyBindService.java
AndroidManifest.xml
TestBindService.app(注意要把aidl文件夹复制过来)
activity_main.xml
Activity.java(注意)
package com.bluelesson.testbindservice;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.IBinder;import android.os.RemoteException;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.EditText;import android.widget.TextView;import com.bluelesson.bindservice.IPersonListenerAIDL;public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);myServiceConnection = new MyServiceConnection();}private MyServiceConnection myServiceConnection;// private MyBindService.MyBinder myBinder;IPersonListenerAIDL aidl;public class MyServiceConnection implements ServiceConnection {@Overridepublic void onServiceConnected(ComponentName componentName,IBinder iBinder) {// myBinder = (MyBindService.MyBinder)iBinder;Log.d("15pb", "MyServiceConnection:: onServiceConnected");aidl = IPersonListenerAIDL.Stub.asInterface(iBinder);}@Overridepublic void onServiceDisconnected(ComponentName componentName) {}}public void btnBind(View view) {Intent intent=new Intent("MyBindService");bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);}public void btnUnBind(View view) {Intent intent=new Intent("MyBindService");unbindService(myServiceConnection);stopService(intent);}public void btnQuery(View view) {EditText editText = findViewById(R.id.edit_query);String string = editText.getText().toString();int num = Integer.parseInt(string);if(aidl!=null) {String name = null;try {name = aidl.queryNameById(num);} catch (RemoteException e) {e.printStackTrace();}TextView textView = findViewById(R.id.tv1);textView.setText(name);}}}









