Android alarmmanager implements uninterrupted polling Service

Source: Internet
Author: User

Whether to select round-robin or push based on actual business needs, such as the demand for high real-time messaging, for example, micro-blog notifications or news, it is best to use push. However, if only common message detection such as update check is performed once every half an hour or once an hour, polling is also a good choice because no additional push server is required, you do not need to configure the PUSH Service. In addition, pushing is generally implemented by maintaining persistent connections, which consumes a certain amount of power on the mobile client. Today, we will introduce a method for implementing the polling mechanism on Android-using alarmmanager

In Android, alarmmanager is mainly used to regularly process an event or periodically process an event. For example, the alarm application is implemented using alarmmanager, we will use the regular execution function of alarmmanager to implement the round robin function today. You can also use timer and timertask to execute tasks on a regular basis, or you can open a service to implement the while loop in the thread. But the best solution is to use alarmmanager, which involves an Android system lock mechanism, that is, after the system detects that the system is not active for a period of time, some unnecessary services are closed to reduce resource and power consumption. If timer and service are used for implementation, it is very likely that after the screen is turned off for a period of time, the service will be stopped, and of course the polling will be stopped. You can try this experiment. I have previously written an article that also introduced a mechanism to keep the background awake, "Use wakelock to keep the Android Application awake in the background". for more information, see. Then we will start to use alarmmanager + Service + thread to implement our polling service!

1. Create a new polling tool class pollingutils. Java

Public class pollingutils {// enable the public static void startpollingservice (context, int seconds, class <?> CLS, string action) {// obtain the alarmmanager System Service alarmmanager manager = (alarmmanager) context. getsystemservice (context. alarm_service); // encapsulate the intentintent intent = new intent (context, CLS); intent. setaction (action); pendingintent = pendingintent. getservice (context, 0, intent, pendingintent. flag_update_current); // the start time of the service to be triggered long triggerattime = systemclock. elapsedrealtime (); // use alarmmanger The setrepeating method of sets the interval (seconds) for regular execution and the servicemanager to be executed. setrepeating (alarmmanager. elapsed_realtime, triggerattime, seconds * 1000, pendingintent);} // stop the public static void stoppollingservice (context, class <?> CLS, string action) {alarmmanager manager = (alarmmanager) context. getsystemservice (context. alarm_service); intent = new intent (context, CLS); intent. setaction (action); pendingintent = pendingintent. getservice (context, 0, intent, pendingintent. flag_update_current); // cancels the service manager being executed. cancel (pendingintent );}}

2. Build a polling task and execute pollingservice. Java

Public class pollingservice extends Service {public static final string action = "com. ryantang. service. pollingservice "; private notification mnotification; private icationicationmanager mmanager; @ overridepublic ibinder onbind (intent) {return NULL ;}@ overridepublic void oncreate () {initnotifimanager ();} @ overridepublic void onstart (intent, int startid) {New pollingthread (). start ();} // initialize the notification bar Set private void initnotifimanager () {mmanager = (icationicationmanager) getsystemservice (icationication_service); int icon = R. drawable. ic_launcher; mnotification = new notification (); mnotification. icon = icon; mnotification. tickertext = "New message"; mnotification. defaults | = notification. default_sound; mnotification. flags = notification. flag_auto_cancel;} // The icationicationprivate void shownotification () {Mn appears. Otification. when = system. currenttimemillis (); // navigator to the new activity when click the notification titleintent I = new intent (this, messageactivity. class); pendingintent = pendingintent. getactivity (this, 0, I, intent. flag_activity_new_task); mnotification. setlatesteventinfo (this, getresources (). getstring (R. string. app_name), "you have new message! ", Pendingintent); mmanager. Y (0, mnotification);}/*** polling thread * simulates the asynchronous thread polling to the server * @ author Ryan * @ create 10:18:34 */int count = 0; class pollingthread extends thread {@ overridepublic void run () {system. out. println ("polling... "); count ++; // If (count % 5 = 0) {shownotification (); system. out. println ("New message! ") ;}}@ Overridepublic void ondestroy () {super. ondestroy (); system. Out. println (" service: ondestroy ");}}

3. Enable and stop pollingservice in mainactivity. Java

public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//Start polling serviceSystem.out.println("Start polling service...");PollingUtils.startPollingService(this, 5, PollingService.class, PollingService.ACTION);}@Overrideprotected void onDestroy() {super.onDestroy();//Stop polling serviceSystem.out.println("Stop polling service...");PollingUtils.stopPollingService(this, PollingService.class, PollingService.ACTION);}}

Iv. Running Effect

After running the project, you can view the output on the console. A notification is sent every 5s. When you exit the activity, the polling service stops, which achieves the expected effect, the service will not be stopped for a long time after the screen lock, because alarmmanager is a system and service. The demo effect is as follows:

On the mobile phone, we can see the pop-up notification information. Click the notification to go to the message interface:


When you enter the Message Details activity, the Message notification in the top status bar is canceled. You can also cancel the Message notification display at the top of the status bar by using the following method:

NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);manager.cancelAll();

The above shows how to use alarmmanger to implement round robin. If you have any shortcomings or defects, please leave a message to add them. The above code is only part of it. If you need the source code of the project, you can clone it on GitHub: https://github.com/tangren03/RTPollingDemo

To join our QQ group or public account, see: Ryan's
Zone public account and QQ Group

At the same time, you are welcome to follow my Sina Weibo chat with me: @ Tang Ren _ Ryan


If this article is useful to you, click "share" in the lower right corner or share it with others!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.