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.
Static registration of Android. Intent. Action. time_tick listeners
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); } }
Three methods prevent your service from being "accelerated with one click" or killed by the System