Android method to implement the Service restart

  • 2020-06-19 11:42:38
  • OfStack

The example in this article shows how Android implements an Service restart. Share to everybody for everybody reference. The details are as follows:

When doing APP, we might need a backend service 1 running directly from the Service component.

But the service may be killed under the following circumstances:

A. User manually clicks stop.
B. Use the third party software (such as 360 Mobile Guard) to clean up. Of course, in this case, other processes besides system service will also be killed unless you contact the phone manufacturer.

At this time, it may be necessary to restart the service. After surfing the Internet for a long time, I mentioned using Timer and AlarmManager to start Service intermittently (after receiving the registered broadcast, start Service). I realized it and found that it still could not be satisfied in the case of B.

I installed a kaka driver assistant on my mobile phone, and found that in the case of B, after killing, the service started automatically after a period of time, and observed Log printing.

07-12 14:12:15.735: I/HadesLee(1456): Receiver,action=android.intent.action.USER_PRESENT
07-12 14:12:15.745: I/HadesLee(1456): KakaService.onCreate....
07-12 14:12:15.745: I/HadesLee(1456): KakaService.onStartCommand,flags=2,startId=1
07-12 14:12:15.755: I/ActivityManager(218): Start proc com.miui.weather2 for broadcast com.miui.weather2/.service.ServiceUpdateWeather: pid=1484 uid=10060 gids={3003}
07-12 14:12:15.755: I/HadesLee(1456): nextRemindTime=null

See this Log, found it to be received android intent. action. USER_PRESENT broadcast, the service start.

android. intent. action. USER_PRESENT corresponding to unlock the phone's screen, o a user can make mobile phone 1 straight the sick have no disease in wake state, so we can receive the broadcast to restart services keep Service1 straight run in the background.

Register the broadcast as OK in the AndroidManifest.xml file and attach the broadcast sent when the phone is switched on.

<receiver android:name="" > 
 <action android:name="android.intent.action.USER_PRESENT" /> 
<receiver android:name="" > 
 <action android:name="android.intent.action.BOOT_COMPLETED" /> 
 <category android:name="android.intent.category.HOME" /> 

public class UserPresentReceiver extends BroadcastReceiver {
  private static final String TAG = "UserPresentReceiver";
  public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub 
    Log.e(TAG, "receive broadcast");
    // do something

I hope this article has been helpful for your Android programming.

Related articles: