一直是聽過其大名,現在終於是學到了。
1、什麼是Service
作爲android四大組件之一,它一直默默付出,不像Activity,可以被人所見。Service一般進行長時間的後臺操作,沒有界面,不是進程也不是線程,比avtivity有更高的優先級。使用Service,有兩步。
- 定義一個繼承Service的子類
- 在AndroidManifest中註冊該Service
Service有一些可以重寫的方法:
IBinder onBind(Intent intent)
:這是必須重寫的方法,當有一個客戶端和Service綁定時,返回的對象可以作爲communication channel
(我不知道怎麼翻譯)和Service通信,如果沒有綁定,返回null。IBinder是一個接口,但是一般不直接實現,而是繼承IBinder的實現類Binder。void onCreate()
:第一次創建Service後會被調用。onStartCommand(Intent intent, int flags, int startId)
:客戶端調用startService(Intent intent)時會被調用。取代了原本的方法onStart(Intent intent, int startId)
void onDestroy()
:Service關閉之前會調用的方法
Service的生命週期
說完了service的一些基本知識,下面看下它的生命週期:
從圖中可以看出Service有兩個運行方式,一個是startService(),另一個是bindService()。所以下面我用兩種方式運行Service來看一下它的運行過程
2、啓動和停止service
寫好Service的子類之後,然後寫了兩個按鈕,爲其添加點擊事件如下
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start:
startService(new Intent(MusicButtonActivity.this, MusicService.class));
break;
case R.id.stop:
stopService(new Intent(MusicButtonActivity.this, MusicService.class));
break;
}
}
然後Service的代碼如下,使用MediaPlayer播放了一段放在res\raw下的音樂
public class MusicService extends Service{
private static final String TAG = MusicService.class.getSimpleName();
//private MyBinder mMyBinder = new MyBinder();
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
mMediaPlayer = MediaPlayer.create(this, R.raw.my);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
mMediaPlayer.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
mMediaPlayer.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
return mMyBinder;
}
@Override
//客戶端和Service解綁時回調的方法
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind");
return super.onUnbind(intent);
}
}
按下start,然後stop,可以看到後臺打印
I/MusicService: onCreate
I/MusicService: onStartCommand
I/MusicService: onDestroy
按下start,然後再按start,後臺打印如下:
I/MusicService: onCreate
I/MusicService: onStartCommand
I/MusicService: onStartCommand
可見onCreate()只會調用一次,當Service已經啓動後,之後就只會調用onStartCommand()方法。
以上使用Service的方法,Activity和Service基本上沒有什麼關聯,兩者之間無法進行通信,交換數據什麼的。所以想實現通信應該用bindService()和unBindService()
3、綁定Service
bindService()裏面有三個參數boolean bindService(Intent service, ServiceConnection conn, int flags)
- 第一個就是通過Intent啓動指定的Service。
- 第二個是ServiceConnection對象,監聽訪問者(clients)和Service的連接情況,我們可以看一下它的代碼
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("disconnected");
}
};
當訪問者和Servive連接成功時會回調onServiceConnected(ComponentName name, IBinder service)
其中service就是onBinder(Intent intent)返回的IBinder對象,通過這個IBinder對象與Service就可以進行通信。另外onServiceDisconnected(ComponentName name)
只會在異常斷開和Service連接時,纔會調用該方法,正常斷開不會回調
- 最後一個指定綁定的時候如果還沒有創建Service,是否自動創建Service,0爲不創建,BIND_AUTO_CREATE爲自動創建。
在上個代碼上修改,在activity裏得到歌曲的總時長(毫秒)。
public class MusicService extends Service{
private static final String TAG = MusicService.class.getSimpleName();
private MyBinder mMyBinder = new MyBinder();
private MediaPlayer mMediaPlayer;
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate");
mMediaPlayer = MediaPlayer.create(this, R.raw.my);
mMediaPlayer.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
// mMediaPlayer.start();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
mMediaPlayer.stop();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
return mMyBinder;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind");
return super.onUnbind(intent);
}
public class MyBinder extends Binder{
public int getProgress(){
return mMediaPlayer.getDuration();
}
}
}
上面onBind()方法返回了一個可以得到歌曲總時長的Binder對象,該對象將會傳給訪問該Service的訪問者。
在activity裏的代碼:
public class MusicButtonActivity extends AppCompatActivity implements View.OnClickListener{
private Button mStop_button;
private Button mStart_button;
MusicService.MyBinder mBinder;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
System.out.println("connected");
//得到傳入的對象
mBinder = (MusicService.MyBinder) service;
//得到了歌曲的時長
int a = mBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("disconnected");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_button);
mStart_button = (Button) findViewById(R.id.start);
mStop_button = (Button) findViewById(R.id.stop);
mStart_button.setOnClickListener(this);
mStop_button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.start:
//startService(new Intent(MusicButtonActivity.this, MusicService.class));
bindService(new Intent(MusicButtonActivity.this, MusicService.class), mServiceConnection, Service.BIND_AUTO_CREATE);
break;
case R.id.stop:
unbindService(mServiceConnection);
//stopService(new Intent(MusicButtonActivity.this, MusicService.class));
break;
}
}
}
點擊start,後臺打印
MusicService: onCreate
MusicService: onBind
點擊stop,後臺打印
08-07 15:59:01.430 14412-14412/com.example.myactionbardemo I/MusicService: onCreate
08-07 15:59:01.485 14412-14412/com.example.myactionbardemo I/MusicService: onBind
08-07 15:59:04.333 14412-14412/com.example.myactionbardemo I/MusicService: onUnbind
08-07 15:59:04.334 14412-14412/com.example.myactionbardemo I/MusicService: onDestroy
通過這種方法可以對Service的數據進行我們需要的操作。
除了以上的兩種情況,如果在Service已經啓動的情況下,再去綁定的話,這個時候如果只是先解綁,在stop才能把Service銷燬
08-07 16:01:29.551 17091-17091/com.example.myactionbardemo I/MusicService: onCreate
08-07 16:01:29.596 17091-17091/com.example.myactionbardemo I/MusicService: onStartCommand
08-07 16:01:29.599 17091-17091/com.example.myactionbardemo I/MusicService: onBind
08-07 16:01:40.265 17091-17091/com.example.myactionbardemo I/MusicService: onUnbind
08-07 16:01:40.275 17091-17091/com.example.myactionbardemo I/MusicService: onDestroy
4、IntentService
我們開篇說過Service不是一個線程,它其實運行在主線程裏,所以它裏面不能處理一個耗時操作,當Service處理耗時操作超過20秒時,將會出現ANR(application not responding)異常,這是不能允許的。如果確實想在Service處理耗時操作,建議另開一條線程處理。除此之外,還可以使用Service的子類IntentService。如下面的代碼
public class MyIntentService extends IntentService{
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
看了下IntentService的源碼
public abstract class IntentService extends Service {
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private String mName;
private boolean mRedelivery;
//處理Intent請求
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
onHandleIntent((Intent)msg.obj);
stopSelf(msg.arg1);
}
}
@Override
//創建了一個單獨的線程
public void onCreate() {
// TODO: It would be nice to have an option to hold a partial wakelock
// during processing, and to have a static startService(Context, Intent)
// method that would launch the service & hand off a wakelock.
super.onCreate();
HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
//發送處理intent請求的消息
@Override
public void onStart(Intent intent, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
/**
* You should not override this method for your IntentService. Instead,
* override {@link #onHandleIntent}, which the system calls when the IntentService
* receives a start request.
* @see android.app.Service#onStartCommand
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
/**
* Unless you provide binding for your service, you don't need to implement this
* method, because the default implementation returns null.
* @see android.app.Service#onBind
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* This method is invoked on the worker thread with a request to process.
* Only one Intent is processed at a time, but the processing happens on a
* worker thread that runs independently from other application logic.
* So, if this code takes a long time, it will hold up other requests to
* the same IntentService, but it will not hold up anything else.
* When all requests have been handled, the IntentService stops itself,
* so you should not call {@link #stopSelf}.
*
* @param intent The value passed to {@link
* android.content.Context#startService(Intent)}.
*/
@WorkerThread
protected abstract void onHandleIntent(Intent intent);
}
IntentService會創建一個HandlerThread這樣的線程來處理所有的Intent請求,而我們只用重寫void onHandleIntent(Intent intent)。IntentService就會幫我們處理。