The example in this article describes how Android implements service restart. Share to everyone for your reference. Specifically as follows:
When we do the app, we may need a backend service that runs all the time and uses the service component.
But services may be killed in the following situations:
A. User clicks stop manually.
B. The use of Third-party software (such as 360 mobile phone guards) to clean up, of course, this way in addition to system services, other processes will certainly be killed, unless with the handset manufacturer contact.
At this time may need to restart the service, read the internet for half a day, mentioned with timer, Alarmmanager to achieve intermittent send broadcast start service (registered broadcast received, start service), I realized the next, found still in the case of B is still not satisfied.
I installed a card driver assistant, found in the case of B, after killing, the service has been automatically started, watch 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
Seeing this log, it was found that the service was started after the broadcast of Android.intent.action.USER_PRESENT was received.
Android.intent.action.USER_PRESENT corresponding to the phone screen unlock, the general user can not be sick of the phone has been in the wake of the state, so we can receive this broadcast service restart, keep the service has been running in the background.
Register the broadcast in the Androidmanifest.xml file OK, incidentally affixed to the mobile phone boot sent broadcast.
?
1 2 3 4 5 6 7 8 9 10 11 |
<receiver android:name= "Com.agilemobi.comac.collect.android.services.UserPresentReceiver" > < intent-filter> <action android:name= "Android.intent.action.USER_PRESENT"/> </intent-filter> </ receiver> <receiver android:name= "Com.agilemobi.comac.collect.android.services.BootReceiver" > < intent-filter> <action android:name= "Android.intent.action.BOOT_COMPLETED"/> <category " Android.intent.category.HOME "/> </intent-filter> </receiver> |
?
1 2 3 4 5 6 7 8 9 |
public class Userpresentreceiver extends Broadcastreceiver {private static final String TAG = "Userpresentreceiver"; @Ove Rride public void OnReceive (context context, Intent Intent) {//TODO auto-generated Method Stub log.e (TAG, "Receive broad" Cast "); Do something}} |
I hope this article will help you with your Android program.