Three methods prevent your Service from being "accelerated with one click" or killed by the System
Basically, we all know that improving the service priority can greatly protect your service from being killed due to insufficient memory. Of course, the system only kills the lower-priority kill first, if the memory is not enough, your service will be killed.
1. android: persistent = "true"
The resident Memory attribute is invalid for third-party apps. The following is an official description.
Android: persistent
Whether or not the application shocould remain running at all times-"true" if it shocould, and "false" if not. the default value is "false ". applications shocould 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. You can listen to the Intent. ACTION_TIME_TIC system clock broadcast. The system sends this broadcast at intervals. when the service is killed, it starts up through broadcast at intervals.
Dynamically register android. intent. action. TIME_TICK listener
Determine whether the service is started
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;}
After receiving the broadcast, determine whether to start the service. If it is not started, start it.
if(intent.getAction().equals(Intent.ACTION_TIME_TICK)) {if (!isServiceRunning(name)) { Intent mIntent = new Intent(context, MyService.class); context.startService(mIntent); } }