基本上大家都知道提高service優(yōu)先級可以在很大程度上讓你的service免于因為內(nèi)存不足而被kill,當(dāng)然系統(tǒng)只是在此時先把優(yōu)先級低的kill掉,如果內(nèi)存還是不夠,也會把你的service干掉的. 1.android:persistent="true" 常駐內(nèi)存屬性對第三方app無效,下面是官方說明 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將其放置前臺 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)聽Intent.ACTION_TIME_TIC系統(tǒng)時鐘廣播,系統(tǒng)每隔一段時間發(fā)送這個廣播,當(dāng)service被殺死的時候,隔一段時間通過廣播啟動 靜態(tài)注冊android.intent.action.TIME_TICK監(jiān)聽 判斷service是否啟動 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; } 接受到廣播后判斷是否啟動該service 若沒有啟動就啟動它 if(intent.getAction().equals(Intent.ACTION_TIME_TICK)) { if (!isServiceRunning(name)) { Intent mIntent = new Intent(context, MyService.class); context.startService(mIntent); }} |
|