Service components are often encountered in Android development and are often used as background services,
Need to be kept running at all times to handle some of the necessary tasks (see no one).
Service components are often encountered in Android development, often as a back-office service that needs to be kept running at all times and is responsible for handling some of the necessary (see no-man) tasks. Some security software, such as 360, will have the ability to end the process, if you do not maintain the service, it will be killed.
How to keep the service running state is now to be explained, the core is the use of Android system broadcast, this will not be affected by other software of the resident program to trigger its own program to check the running state of the service, if killed, and then up.
I use the system broadcast is Intent.action_time_tick, this broadcast is sent every minute, we can check the running status of the service every minute, if it has been completed, restart the service.
Below is the specific code and considerations:
1, the use of Intent.action_time_tick
We know that broadcast registration has static registration and dynamic registration, but this system broadcast can only be used in the way of dynamic registration. That is, you cannot receive this broadcast by registering in Manifest.xml, only by registering it with the Registerreceiver () method in your code.
Register for the broadcast in Thisapp extends application:
Intentfilter filter = Newintentfilter (Intent.action_time_tick);
Mybroadcastreceiver receiver = new Mybroadcastreceiver ();
Registerreceiver (receiver, filter);
In the onreceive of the broadcast receiver Mybroadcastreceiver extends Broadcastreceiver.
if (Intent.getaction (). Equals (Intent.action_time_tick)) {
Check Service status
}
2, service inspection and start-up
Boolean isservicerunning = false;
Activitymanager manager = (Activitymanager) thisapp.getcontext (). Getsystemservice (Context.activity_service);
For (Runningserviceinfo service:manager.getRunningServices (integer.max_value)) {
if ("So.xxxx.WidgetUpdateService". Equals (Service.service.getClassName ()))
The class name of the service
{
Isservicerunning = true;
}
}
if (!isservicerunning) {
Intent i = new Intent (context, widgetupdateservice.class);
Context.startservice (i);
}
Another topic, the service boot up.
The implementation is similar to the above, and also starts the service by monitoring the system broadcast on the boot. But in fact you do the top of the check will not do the boot, because after a two minutes will be through the top of the program to start the service. The code is as follows:
if (Intent.getaction (). Equals (intent.action_boot_completed)) {
Intent i = new Intent (context, logservice.class);
Context.startservice (i);
}
Self-start and hold for Android service background services process