Service components are often used in android development. They are often used as backend services and must always run and be responsible for handling tasks that are not necessarily human. Some security software, such as 360, may end the process. If the Service is not maintained, it will be killed.
How to maintain the running status of the Service is explained now. The core is to use the ANDROID system broadcast. This resident program that will not be affected by other software will trigger its own program to check the running status of the Service, if it is killed, it will be restarted.
The system broadcast I use is Intent. ACTION_TIME_TICK. This broadcast is sent once every minute. We can check the running status of the Service once every minute. If the broadcast has ended, restart the Service.
Below are the specific code and precautions:
1. Use of Intent. ACTION_TIME_TICK
We know that broadcast registration includes static registration and dynamic registration, but this system broadcast can only be used through dynamic registration. That is, you cannot receive this broadcast by registering in manifest. xml. You can only register the broadcast in the code using the registerReceiver () method.
Register 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 the Service status
- }
2. Check and start the Service
- 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 ()))
- // Service class name
- {
- IsServiceRunning = true;
- }
- }
- If (! IsServiceRunning ){
- Intent I = new Intent (context, WidgetUpdateService. class );
- Context. startService (I );
- }
Another topic is Service startup.
Similar to the preceding implementation, the Service is started by monitoring the system broadcast of the startup. However, after you perform the above check, you will not start the Service after boot, because the above program will start the Service in a minute or two. The Code is as follows:
- if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
- Intent i = new Intent(context, LogService.class);
- context.startService(i);
- }