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; } }
下面是創建一個專門的Binder來對下載功能進行管理的代碼
public class MyService extends Service{ private DownloadBinder mBinder = new DownloadBinder(); class DownloadBinder extend Binder{ public void startDownload(){ Log.d("MyService", "startDownload executed"); } public int getProgress(){ Log.d("MyService", "getProgress executed"); return 0; } } @Override public IBinder onBind(Intent intent){ return mBinder; } ... }