Service生命週期:
如圖:
代碼測試:
繼承Swevice:
public class Myservice extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.i("woyaokk", "====================onCreate==============");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("woyaokk","====================onBind==============");
return new MyBinder();
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
Log.i("woyaokk", "====================onBind==============");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("woyaokk","====================onStartCommand==============");
return super.onStartCommand(intent, flags, startId);
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("woyaokk","====================onUnbind==============");
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.i("woyaokk","====================onDestroy==============");
super.onDestroy();
}
class MyBinder extends Binder {
/**
* 獲取Service的方法
*/
public Myservice getService(){
return Myservice.this;
}
}
}
註冊:
<service android:name=".Myservice"></service>
啓動:
Intent intent=new Intent(MainActivity.this,Myservice.class);
MainActivity.this.startService(intent);
停止:
Intent intent=new Intent(MainActivity.this,Myservice.class);
MainActivity.this.stopService(intent);
當使用兩次啓動方法,一次停止方法,返回:
由此可知:通過startService方法啓動Service則會調用OnCreate方法和OnStartCommand方法,並且多次調用startService方法只會調用由此OnCreate,但會掉用多次onStartCommand,銷燬時調用onDestory
綁定:
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 建立連接
Myservice.MyBinder binder = (Myservice.MyBinder) service;
myService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// 連接斷開
}
};
Intent intent=new Intent(MainActivity.this,Myservice.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
解綁:
unbindService(serviceConnection);
聲明週期:
由此可知:通過啓動通過綁定啓動Service調用onCreate和onBind方法,解綁時調用onUnbind和onDestory方法;
注意:
Service和Thread本質上沒有半毛錢關係,Service同樣運行在主線程中,所以一樣不能執行耗時操作,如果需要執行耗時操作,可以開啓異步線程或者繼承IntentService