This article describes the implementation of user online heartbeat function based on AlarmManager. Share it for your reference, as follows:
Heartbeat should be used when doing instant communication or other operations such as checking whether it is online. The most commonly used AlarmManager global timer is implemented.
The use mechanism of AlarmManager is called a global timer, and some is called an alarm clock. In fact, its function is somewhat similar to Timer. There are two similar uses: (1)Perform an action after a specified duration(2)Perform an operation periodically
The AlarmManager object can be used in conjunction with Intent, and can be enabled regularly, a BroadCast is sent, or a Service is enabled.
The following code introduces the use of two timing methods in detail:
(1) Perform an operation after the specified time
//Operation: Send a broadcast, and after the broadcast is received, Toast prompts the timing operation to be completed. Intent intent =new Intent(, );("short"); PendingIntent sender= (, 0, intent, 0); //Set a time after five secondsCalendar calendar=(); (()); (, 5); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); (AlarmManager.RTC_WAKEUP, (), sender); //or simplify the following//(AlarmManager.RTC_WAKEUP, ()+5*1000, sender); (, "Alarm is turned on in five seconds", Toast.LENGTH_LONG).show();
Note: Remember to register
public static class alarmreceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if(().equals("short")){ (context, "short alarm", Toast.LENGTH_LONG).show(); }else{ (context, "repeating alarm", Toast.LENGTH_LONG).show(); } } }
(2) Perform a certain operation periodically
Intent intent =new Intent(, ); ("repeating"); PendingIntent sender=PendingIntent .getBroadcast(, 0, intent, 0); //Start timelong firstime=(); AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);//5 seconds per cycle, constantly sending broadcasts(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5*1000, sender);
AlarmManagersetRepeating()
Equivalent to TimerSchedule(task,delay,peroid);
The difference is that Timer method specifies how long it takes to start periodic execution of tasks;
Cancel of AlarmManager: (It should be noted that the cancelled Intent must be absolutely consistent with the startup Intent to support cancellation of AlarmManager)
Intent intent =new Intent(, ); ("repeating"); PendingIntent sender=(, 0, intent, 0); AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE); (sender);
For more information about Android related content, please check out the topic of this site:Android View View Tips Summary》、《Android programming activity operation skills summary》、《Android layout layout tips summary》、《Android development introduction and advanced tutorial》、《Android resource operation skills summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.