1.服務(wù)是什么
服務(wù)是Android在實現(xiàn)后臺運行時的解決方案,適用于不用和用戶有界面交互的后臺長期運行任務(wù)。
注意
- 服務(wù)并不是獨立的進程,它依賴于創(chuàng)建服務(wù)的應(yīng)用程序進程,當應(yīng)用被殺時,服務(wù)也終止
- 服務(wù)也不是在子線程中運行的,默認情況都是在主線程執(zhí)行,因此長時操作也要開啟子線程來執(zhí)行。
2.多線程編程
2.1 Android異步消息處理機制:Handler
- Message:可以在線程間傳遞的消息,一般通過msg.what來傳遞想要主/子線程想要做的消息
- Handler:消息的處理者,用于發(fā)送以及處理收到的消息。
- MessageQueue:消息隊列,它用于存放所有通過Handler發(fā)送的消息,這些消息則是存儲在這個隊列中,等待被處理。每個線程只有一個MessageQueue對象。
- Looper:MessageQueue的管家, 調(diào)用Looper的loop方法后,開始進入無限循環(huán),發(fā)現(xiàn)MessageQueue中有msg的時候,就把它取出并傳給Handler的handleMessage方法中。

Android異步處理消息流程圖
2.2 使用AsyncTask
AsyncTask是android為開發(fā)者提供的異步工具??梢苑奖汩_發(fā)者在子線程中對UI進行操作。
private class MyAsyncTask extends AsyncTask<Void, Integer, Boolean> {
//后臺線程執(zhí)行前的準備工作防止這個方法里
@Override
protected void onPreExecute() {
super.onPreExecute();
}
//后臺執(zhí)行長時操作
@Override
protected Boolean doInBackground(Void... voids) {
return null;
}
//在doInBackground 方法中調(diào)用onProgressUpdate方法時,執(zhí)行該方法(主線程里執(zhí)行)
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
//后臺任務(wù)執(zhí)行完畢時自動調(diào)用,在主線程里執(zhí)行
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
……
……
//執(zhí)行AsyncTask
new MyAsyncTask.execute()
AsyncTask的三個范型參數(shù):Params, Progress, Result:分別用來傳入?yún)?shù),表示進度,表示執(zhí)行結(jié)果。
3.服務(wù)的基本用法
3.1 啟動和停止服務(wù)
Intent intent = new Intent(this, MyService.class);
startService(intent);
stopService(intent);
3.2 Service的基本定義
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
//Called when Service being created for the first time
@Override
public void onCreate() {
super.onCreate();
}
//Called when Service is called by outside every time
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
//Called when Service being destroyed, recycle useless resources in this function
@Override
public void onDestroy() {
super.onDestroy();
}
}
3.3 服務(wù)和其它組件通信 Binder
在服務(wù)端(Service)創(chuàng)建一個binder提供給客戶端(這里是Activity);客戶端可以通過調(diào)用binder中的public方法來獲取服務(wù)中的相關(guān)信息。
服務(wù)度端定義binder
private DownloadBinder mBinder = new DownloadBinder();
//the server side returns a IBinder for client to access opened functions of the binder
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
class DownloadBinder extends Binder {
public void startDownload() {
Log.i("lyh", "start download");
}
public int getProgress() {
Log.i("lyh", "download progress");
return 0;
}
}
客戶端連接服務(wù),并獲取binder
public class DownloadTestActivity extends AppCompatActivity {
private MyService.DownloadBinder mIBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIBinder = (MyService.DownloadBinder) service;
mIBinder.startDownload();
mIBinder.getProgress();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_test);
//bind service
Intent intent = new Intent(this, MyService.class);
/**
* Flag for {@link #bindService}: automatically create the service as long
* as the binding exists. Note that while this will create the service,
* its {@link android.app.Service#onStartCommand}
* method will still only be called due to an
* explicit call to {@link #startService}. Even without that, though,
* this still provides you with access to the service object while the
* service is created.
**/
bindService(intent, connection, BIND_AUTO_CREATE);
//unbind service:
//unbindService(connection);
}
}