簡介
- Service是Android應(yīng)用程序中的一個組件病梢,與用戶不進行交互,可以長期的執(zhí)行在后臺觅彰。當(dāng)新建一個服務(wù)的時候需要在AndroidManifest.xml文件中進行聲明钮热。服務(wù)可以通過Context.startService()和Context.bindService()來進行啟動。前者就是開啟一個普通的服務(wù)后者是將調(diào)用者與服務(wù)進行綁定飒责,來進行長時間的通信仆潮。
- 服務(wù)類似于其他應(yīng)用程序的對象,運行在主線程中檐晕。這就意味著你如果在服務(wù)中進行耗時的操作蚌讼,你需要開啟一個子線程去處理這個操作,不然在服務(wù)中超過20秒未響應(yīng)會發(fā)生ANR導(dǎo)致程序崩潰芥喇。IntentService的出現(xiàn)就是為了解決在服務(wù)中操作耗時任務(wù)的凰萨。
服務(wù)的開啟方式
兩種方式
- startService(Intent intent)
- bindService(Intent intent,ServiceConnection Connection,int flags);
兩種方式的區(qū)別(和生命周期一起分析)
- startService()
- startService()開啟服務(wù)時服務(wù)執(zhí)行的生命周期方法是 onCreate() --> onStartCommand() --> onDestroy()
- 其中onCreate()會在服務(wù)第一次創(chuàng)建的時候調(diào)用,當(dāng)多次調(diào)用startService方法的時候,onCreate只會執(zhí)行一次簇搅,而onStartCommand會執(zhí)行多次,onDestroy方法會在服務(wù)銷毀的時候進行調(diào)用
- 服務(wù)的銷毀 該方式下啟動的服務(wù)可以調(diào)用stopService(Intent intent)或者stopSelf()來進行服務(wù)的銷毀。
- bindService
- bindService綁定服務(wù)時服務(wù)執(zhí)行的生命周期方法是 onCreate() --> onBind --> onUnbind--> onDestroy
- onCreate囚枪,onBind 會在bindService第一次調(diào)用的時候去執(zhí)行劳淆,如果多次調(diào)用bindService,onCreate和onBind也就執(zhí)行一次括勺,onUnbind和onDestroy會在解綁服務(wù)的時候進行調(diào)用。
- 服務(wù)的解綁 該方式下綁定的服務(wù)需要調(diào)用unbindService(ServiceConnection mConnection)方法來進行服務(wù)的解綁操作奈辰。
混合開啟服務(wù)
- 所謂的混合開啟服務(wù)就是即調(diào)用了startService又調(diào)用了bindService方法來啟動服務(wù)拾氓。
- 這里我們分兩種混合開啟方式
startService() --> bindService()
start1.jpg-
接著我們配合這種開啟方式咙鞍,去關(guān)閉服務(wù)
stopService()-->unbindService()
stop1-1.jpg觀察生命周期方法的執(zhí)行發(fā)現(xiàn)趾徽,先執(zhí)行stopService()并沒有把服務(wù)銷毀孵奶,當(dāng)調(diào)用ubindService()的時候?qū)⒎?wù)解綁了,并且將服務(wù)銷毀了了袁。
unbindService()-->stopService()
stop1-2.jpg
-
接著觀察生命周期方法载绿,先執(zhí)行unbindService()方法時執(zhí)行了解綁服務(wù)的操作,當(dāng)調(diào)用stopService()才將服務(wù)給銷毀了怀浆。
bindService() --> startService()
* 接著我們配合這種開啟方式怕享,去關(guān)閉服務(wù)
stopService()-->unbindService()
unbindService()-->stopService()
服務(wù)與Activity之間的通信方式
-
Binder對象
通過綁定服務(wù)的方式開啟服務(wù)函筋,在Service中創(chuàng)建一個Binder,然后聲明一個Binder對象灌诅,通過onBind()方法將這個Binder對象返回含末,然后在Activity中實現(xiàn)ServiceConnection接口,實現(xiàn)內(nèi)部的方法挎袜,然后在onServiceConnected方法中將Service中onBind()返回的Binder對象獲取到,然后通過Binder對象去調(diào)用Binder類中的方法(一般都是自定義的)紊搪,這就完成了Service與Activity之間的通信全景,也成功的實現(xiàn)了Activity調(diào)用服務(wù)中的方法了。
-
Intent對象
通過startService方式開啟服務(wù)滞伟,需要傳遞intent對象到Service的onStartCommand方法中炕贵,通過intent對象可以實現(xiàn)Activity到Service之間通信。(就是Activity傳輸數(shù)據(jù)到Service中)亩钟。
-
廣播(Broadcast)
- 同樣鳖轰,在Service中執(zhí)行一些耗時的操作的時候,然后將執(zhí)行的結(jié)果通知到Activity中蕴侣,然后更新UI睛蛛。可以通在子線程中發(fā)送廣播忆肾。然后在Activity中接收到注冊好的廣播。獲取到結(jié)果旭从,結(jié)果的獲取是在UI線程中场仲,直接更新UI。
- 在Activity中聲明一個廣播鸽素。
class MyBroadCast extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String data = intent.getStringExtra("flag"); Log.d(TAG, "onReceive: "+data); } }
- 在Activity中注冊一個廣播亦鳞,用來接受相同action發(fā)來的廣播棒坏,在綁定服務(wù)或者開啟服務(wù)的時候注冊這個廣播坝冕。
public void registerBroadcast(){ MyBroadCast myBroadCast = new MyBroadCast(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("com.broadcast.mybroadcast"); registerReceiver(myBroadCast,intentFilter); } bindService.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bindIntent = new Intent(MainActivity.this, ServiceLifeMethod.class); // Context.BIND_AUTO_CREATE 表示 活動和服務(wù)進行綁定后自動創(chuàng)建服務(wù) //使得onCreate方法得到執(zhí)行瓦呼,onStartCommand方法不會執(zhí)行 bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE); //注冊服務(wù) registerBroadcast(); } });
- 在服務(wù)中合適的地方發(fā)送廣播,在Activity中聲明好的廣播的onReceive方法中獲取廣播發(fā)來的數(shù)據(jù)磨澡。
/** * 發(fā)送廣播 */ public void sendBroadcast(){ Intent intent = new Intent(); intent.setAction("com.broadcast.mybroadcast"); intent.putExtra("flag","dashingqi"); sendBroadcast(intent); } class MyBroadCast extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String data = intent.getStringExtra("flag"); Log.d(TAG, "onReceive: "+data); } }
接口回調(diào)
當(dāng)Service執(zhí)行一些耗時的操作時蹋辅,執(zhí)行完畢需要通知Activty來更新數(shù)據(jù)侦另,可以通過接口回調(diào)方式尉共。
寫一個接口類,提供調(diào)用的方法袄友。
public interface MyInterface {
void get();
void getMethod();
}
- 在Service中的自定義Binder類中剧蚣,提供一個對外獲取Service的方法。
class MyBinder extends Binder {
public ServiceLifeMethod getService(){
return ServiceLifeMethod.this;
}
}
- 在Service中提供一個對外注冊接口的方法礼搁,通過接口傳進來的接口實例目尖,在合適的地方來調(diào)用接口的方法。
private MyInterface myInterface;
public void addCallBack(MyInterface myInterface){
this.myInterface = myInterface;
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy: ");
super.onDestroy();
myInterface.get();
}
- Activity實現(xiàn)接口類饮戳,實現(xiàn)接口中的方法洞拨,在方法中書寫回調(diào)方法的邏輯,在ServiceConnection接口的回調(diào)方法onServiceConnected中獲取到Service實例烦衣,去調(diào)用Service提供的注冊接口的方法。
public class MainActivity extends AppCompatActivity implements MyInterface
@Override
public void get() {
//Service的onDestroy()發(fā)放得到執(zhí)行
Log.d(TAG, "get: onDestroy方法得到執(zhí)行");
}
@Override
public void getMethod() {
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ServiceLifeMethod.MyBinder myBinder = (ServiceLifeMethod.MyBinder) service;
Log.d(TAG, "onServiceConnected: ");
ServiceLifeMethod myBinderService = myBinder.getService();
myBinderService.addCallBack(MainActivity.this);
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(TAG, "onServiceDisconnected: ");
}
};
- 通過bindService方法去綁定服務(wù)涣脚。
bindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bindIntent = new Intent(MainActivity.this, ServiceLifeMethod.class);
// Context.BIND_AUTO_CREATE 表示 活動和服務(wù)進行綁定后自動創(chuàng)建服務(wù) 使得onCreate方法得到執(zhí)行寥茫,onStartCommand方法不會執(zhí)行
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
});
服務(wù)的使用場景
- 音樂的播放
- 下載
問題記錄
如何保證Service不被殺死
- 提高進程的優(yōu)先級,降低進程被殺死的概率芭梯。
- 啟動前臺服務(wù)弄喘。
- 提升服務(wù)的優(yōu)先級,在AndroidManifest.xml文件中服務(wù)中設(shè)置android:priority="1000"這個屬性為最高的優(yōu)先級累奈。
- 監(jiān)控手機的鎖屏或者解鎖事件急但,在鎖屏?xí)r啟動一個像素的activity,在用戶解鎖時將Activity銷毀戒努。
- 在進程殺死之后镐躲,進行拉活。
- 注冊高頻率的廣播接收器萤皂,比如網(wǎng)絡(luò)的變化敌蚜,解鎖手機屏幕,開機等弛车。
- 雙進程相互喚起。
- 依靠系統(tǒng)喚起喻括。
- 依靠第三方
Android這邊依靠終端的不同贫奠,去集成不同終端的推送望蜡,小米集成小米推送脖律,華為集成華為推送腕侄;