定義
- 後臺運行,不可見,沒有界面
- 優先級 高於Activity
用途
- 播放音樂,記錄地理信息位置的改變,監聽某種動作
注意
- 運行在主線程,不能用它來做耗時的請求或者動作
- 可以在服務中開一個線程,在線程中做耗時的動作
類型
- 本地服務:用在程序內部。 startService stopService stopSelf stopSelfResult 與 bindService unbindServicee
- 遠程服務:Android 系統內部的應用程序之間。 (不可跨手機) IBinder接口。
服務與Activity的綁定
1、新建class
public class MyService extends Service {}
2、如果用startService方法,則需重寫onStartCommand方法:
public int onStartCommand(Intent intent, int flags, int startId) {}
3、如果用onBind方法:(主要說明這個方法):
private DonwloadBinder mBinder = new DonwloadBinder();
class DonwloadBinder extends Binder {
public void startDownload() {
Log.d(TAG, "startDownload: ");
}
public int getProcess() {
Log.d(TAG, "getProcess: ");
return 0;
}
}
4、在mainactivity中創建connection:
private MyService.DonwloadBinder donwloadBinder;
private static final String TAG = "MainActivity";
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
donwloadBinder = (MyService.DonwloadBinder) iBinder;
donwloadBinder.startDownload();
donwloadBinder.getProcess();
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
5、綁定服務:
Intent bindIntent = new Intent(this , MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE);
6、解除綁定:
unbindService(connection);
AsyncTask 與 Service結合使用
1、新建Task類:
public class DownloadTask extends AsyncTask<String,Integer,Integer> {}
2、重寫doInBackground方法:
@Override
protected Integer doInBackground(String... strings) {
return null;
}
3、