Problem: The app always performs a task periodically, such as checking for updates on the server or alerting the user to something.
Solution: Use Alarmmanager to manage and execute tasks. Alarmmanager can be used to plan for future single or repetitive operations, even when the app is not running .
Alarmmanager a component that executes various systems, such as activity, broadcast, Receiver, and Service, by issuing a pendingintent to emit a warning when triggered.
Write the triggered Broadcastreceiver
ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.widget.Toast; Public classAlarmreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {//can do an interesting operation, we just show the current time hereCalendar now =calendar.getinstance (); Java.text.DateFormat Formatter=simpledateformat.gettimeinstance (); Toast.maketext (Context, Formatter.format (Now.gettime ()),100). Show (); }}
Broadcastreceiver must be declared with the <receiver> tag in the manifest file, otherwise Alarmmanager will not be able to trigger it.
<receiver android:name= ". Alarmreceiver "></receiver>
Settings and cancellation reminders are implemented through pendingintent. We create a intent that directly points to the application's broadcastreceiver and then create a pendingintent from it with Getbroadcast () (because we created a reference to Broadcastreceiver).
ImportAndroid.os.Bundle;ImportAndroid.os.SystemClock;Importandroid.app.Activity;ImportAndroid.app.AlarmManager;Importandroid.app.PendingIntent;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Toast; Public classMainactivityextendsActivityImplementsOnclicklistener {Privatependingintent malarmintent; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); //attach a listener to two buttonsFindviewbyid (R.id.start). Setonclicklistener ( This); Findviewbyid (r.id.stop). Setonclicklistener ( This); //Create reminder triggersIntent launchintent =NewIntent ( This, Alarmreceiver.class); Malarmintent= Pendingintent.getbroadcast ( This, 0, launchintent, 0); } @Override Public voidOnClick (view view) {Alarmmanager Manager=(Alarmmanager) Getsystemservice (Context.alarm_service); LongInterval = 5*1000; Switch(View.getid ()) { CaseR.id.start:toast.maketext ( This, "scheduled", 100). Show (); //Elapsed_realtime triggers a reminder based on time, and if the device is dormant, the device is activated. Manager.setrepeating (Alarmmanager.elapsed_realtime, systemclock.elapsedrealtime () +interval, interval, malarmintent); Break; CaseR.id.stop:toast.maketext ( This, "Canceled", 100). Show (); Manager.cancel (malarmintent); Break; default: Break; } }}