1.生命周期
四个手动调用的方法
手动调用的方法 | 作用 |
startService( ) | 启动服务 |
stopService( ) | 关闭服务 |
bindService( ) | 绑定服务 |
unbindService( ) | 解绑服务 |
五个内部自动调用的方法
内部自动调用的方法 | 作用 |
onCreat( ) | 创建服务 |
onStartCommand( ) | 开始服务 |
onDestory( ) | 销毁服务 |
onBind( ) | 绑定服务 |
onUnbind( ) | 解绑服务 |
其中:
1. onCreat( )和onStartCommand( )的区别:onCreat( )方法实在服务的第一次创建的时候调用,而onStartCommand( )方法则再每次启动服务的时候均会调用。但是每个服务只会存在一个实例。
2. 服务启动了之后会一直保持运行状态,直到stopService( )或者stopSelf( )方法被调用。
3. 当调用了startService( )之后再去调用stopService( ),这是服务中的onDestory( )方法将会被调用,表示服务已经被销毁。同理bindService( )方法和unbindService( )方法类似,但是如果其即调用了startService( )方法有调用了bindService( )方法,那么该服务必须满足stopService( )和unbindService( )两种条件onDestory( )方法才被执行。
2. 活动与服务通信
如果自定义一个MyService来继承Service的话,可以看到onBind( )方法是Service中唯一的一个抽象方法:
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在重写服务时,一般我们会重写四个方法:
1)onCreate():创建服务时调用
2)onStartCommand():每次启动服务时都会调用此方法
3)onDestroy():服务销毁的时候调用
4)onBind():服务的唯一抽象方法,子类中必须实现的方法
以上是简单的重写一个服务而已,如果想要获取到服务中的信息,需要使用BindService(),此方法的构造方法如下所示:
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
return mBase.bindService(service, conn, flags);
}
下面是绑定服务时一个简单的例子:
public class MyService extends Service {
private final static String TAG = "MyService";
public MyService() {
}
private DownLoadBinder downLoadBinder = new DownLoadBinder();
class DownLoadBinder extends Binder {
public void downLoadStart() {
Log.d(TAG, "nothing to do");
}
public int getProgress() {
Log.d(TAG, " Just return Progress");
return 1;
}
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
@Override
public IBinder onBind(Intent intent) {
return downLoadBinder;
}
}
在主程序中绑定此服务:
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downLoadBinder = (MyService.DownLoadBinder) service;
downLoadBinder.downLoadStart();
Log.d(TAG, downLoadBinder.getProgress() + "progress");
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//绑定此服务,并且绑定后自动创建
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
//取消绑定此服务
unbindService(connection);
可以看到当我们在主程序中对服务进行绑定之后,便可以通过此方法获取到服务中的进度之类的信息。需要注意的是,任何一个服务,不仅可以在主程序中进行绑定,在应用程序的任何活动之内,都可以对其进行绑定操作。
但是需要注意的是,服务启动了之后就会一直保持运行状态,知道我们调用了StopService()或者stopSelf()方法,虽然每次调用都会执行一次startCommand()但是,每个服务仅仅存在一个实例,无论调用多少次的startCommand()方法,只需要调用一次stopService()或者stopSelf()方法即可。
3.使用IntentService
上面的服务之类的操作都是在主线程中进行,如果处理一些耗时的操作则容易出现ANR,因此使用IntentService,即在服务中开启一个子线程来进行一些耗时的操作。
但是IntentService是使用工作线程对所有的请求进行逐一处理,只需要实现onHandIntent即可。