Create a Servicebestpractice project, and then add a Longrunningservice class, as shown in the following code:
PackageCom.example.servicebestpractice;Importjava.util.Date;ImportAndroid.app.AlarmManager;Importandroid.app.PendingIntent;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.os.IBinder;ImportAndroid.os.SystemClock;ImportAndroid.util.Log; Public classLongrunningserviceextendsservice{@Override Publicibinder onbind (Intent Intent) {//TODO auto-generated Method Stub return NULL; } @Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) { NewThread (NewRunnable () {@Override Public voidrun () {LOG.D ("Longrunningservice", "executed at" +NewDate (). toString ()); }}). Start (); Alarmmanager Manager=(Alarmmanager) Getsystemservice (Alarm_service); intAnhour = 60 * 60 * 1000;//This is the number of milliseconds in an hour. LongTriggerattime = Systemclock.elapsedrealtime () +Anhour; Intent I=NewIntent ( This, Alarmreceiver.class); Pendingintent Pi= Pendingintent.getbroadcast ( This, 0, I, 0); Manager.set (Alarmmanager.elapsed_realtime_wakeup, Triggerattime, pi); return Super. Onstartcommand (Intent, flags, Startid); }}
Create a new Alarmreceiver class and let it inherit from Broadcastreceiver, as shown in the following code:
PackageCom.example.servicebestpractice;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent; Public classAlarmreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {Intent i=NewIntent (context, Longrunningservice.class); Context.startservice (i); }}
Next we need to start the longrunningservice at the time of opening the program and modify the code in the mainactivity as follows:
PackageCom.example.servicebestpractice;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intent I=NewIntent ( This, Longrunningservice.class); StartService (i); }}
Finally, don't forget that the broadcast receivers and services we use are registered in Androidmanifest.xml, as shown in the following code:
<android:name= ". Longrunningservice "> </service> < android:name= ". Alarmreceiver "> </receiver>
Best practices for services-timed tasks performed in the background