|
基本上大家都知道提高service優(yōu)先級(jí)可以在很大程度上讓你的service免于因?yàn)閮?nèi)存不足而被kill,當(dāng)然系統(tǒng)只是在此時(shí)先把優(yōu)先級(jí)低的kill掉,如果內(nèi)存還是不夠,也會(huì)把你的service干掉的. 1.android:persistent="true" 常駐內(nèi)存屬性對(duì)第三方app無(wú)效,下面是官方說(shuō)明 android:persistent Whether or not the application should remain running at all times — "true" if it should, and "false" if not. The default value is "false". Applications should not normally set this flag; persistence mode is intended only for certain system applications. 2.startForeground將其放置前臺(tái) Notification notification = new Notification();notification.flags = Notification.FLAG_ONGOING_EVENT;notification.flags |= Notification.FLAG_NO_CLEAR;notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;startForeground(1, notification); 3.可以監(jiān)聽(tīng)I(yíng)ntent.ACTION_TIME_TIC系統(tǒng)時(shí)鐘廣播,系統(tǒng)每隔一段時(shí)間發(fā)送這個(gè)廣播,當(dāng)service被殺死的時(shí)候,隔一段時(shí)間通過(guò)廣播啟動(dòng) 靜態(tài)注冊(cè)android.intent.action.TIME_TICK監(jiān)聽(tīng) 判斷service是否啟動(dòng) public boolean isServiceRunning(String serviceName) { ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); for (RunningServiceInfo service :manager.getRunningServices(Integer.MAX_VALUE)) { if(serviceName.equals(service.service.getClassName())) { return true; } } return false; }接受到廣播后判斷是否啟動(dòng)該service 若沒(méi)有啟動(dòng)就啟動(dòng)它 if(intent.getAction().equals(Intent.ACTION_TIME_TICK)) { if (!isServiceRunning(name)) { Intent mIntent = new Intent(context, MyService.class); context.startService(mIntent); }}
|
|
|