Android Alarmmanager for uninterrupted polling service

Source: Internet
Author: User

In the acquisition of the message is to choose polling or push to be based on the actual business needs of the technology selection, such as the high real-time information on the demand, such as Weibo new notice or news, it is best to use the push. But if the general message detection, such as update check, may be half an hour or one hours, then polling is also a good choice, because there is no need to build a push server, no additional configuration of the push service. In addition, the push is now generally implemented in a way that maintains long connections and consumes a certain amount of power in the mobile client. Today is a way to implement a polling mechanism on Android-using Alarmmanager

Alarmmanager is primarily used in Android to handle an event on a regular basis, or to process an event regularly, such as an alarm app that is implemented using Alarmmanager, and we use Alarmmanager's regular execution function to implement polling today. For regular tasks can also be implemented with a timer and timertask, you can also open a service in the thread with a while loop to achieve. But the best option is to choose Alarmmanager, which involves an Android system lock mechanism that, after detecting a period of inactivity, shuts down some unnecessary services to reduce resource and power consumption. Using a timer and service is likely to happen when the screen goes out and the service is stopped, and of course the polling is stopped. You can experiment with this, and before I wrote an article that also describes a mechanism for keeping the background wake up, "using Wakelock to keep the Android app awake in the background" is interesting to see. Then start using Alarmmanager+service+thread to implement our polling service!

First, the new polling tool class Pollingutils.java

 Public classPollingutils {//turn on polling service     Public Static voidStartpollingservice (Context context,intSeconds, class<?>cls,string Action) {        //Get Alarmmanager System ServicesAlarmmanager Manager =(Alarmmanager) context. Getsystemservice (Context.alarm_service); //packaging needs to perform service intentIntent Intent =NewIntent (context, CLS);        Intent.setaction (action); Pendingintent pendingintent= Pendingintent.getservice (Context,0, intent, pendingintent.flag_update_current); //start time of the triggering service        LongTriggerattime =Systemclock.elapsedrealtime (); //Use the Setrepeating method of Alarmmanger to set the time interval (seconds seconds) for periodic execution and the service that needs to be performedmanager.setrepeating (Alarmmanager.elapsed_realtime, triggerattime, seconds* +, pendingintent); }    //Stop Polling service     Public Static voidStoppollingservice (context context, class<?>cls,string Action) {Alarmmanager Manager=(Alarmmanager) context. Getsystemservice (Context.alarm_service); Intent Intent=NewIntent (context, CLS);        Intent.setaction (action); Pendingintent pendingintent= Pendingintent.getservice (Context,0, intent, pendingintent.flag_update_current); //Cancel a service that is executingManager.cancel (pendingintent); }}

Second, build polling task execution Pollingservice.java

 Public classPollingservice extends Service { Public StaticFinal String ACTION ="Com.ryantang.service.PollingService"; PrivateNotification mnotification; PrivateNotificationmanager Mmanager; @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Initnotifimanager (); } @Override Public voidOnStart (Intent Intent,intStartid) {        NewPollingthread (). Start (); }    //initializing the notification bar configuration    Private voidInitnotifimanager () {Mmanager=(Notificationmanager) Getsystemservice (Notification_service); inticon =R.drawable.ic_launcher; Mnotification=NewNotification (); Mnotification.icon=icon; Mnotification.tickertext="New Message"; Mnotification.defaults|=Notification.default_sound; Mnotification.flags=Notification.flag_auto_cancel; }    //Eject Notification    Private voidshownotification () {Mnotification.when=System.currenttimemillis (); //Navigator to the new activity when click the notification titleIntent i =NewIntent ( This, Messageactivity.class); Pendingintent 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.notify (0, mnotification); }    /** * Polling thread * Simulates an asynchronous thread polling to the server * @Author Ryan * @Create 2013-7-13 morning 10:18:34*/    intCount =0; classPollingthread extends Thread {@Override Public voidrun () {System. out. println ("Polling ..."); Count++; //Popup Notification when count can be divisible by 5            if(Count%5==0) {shownotification (); System. out. println ("New message!"); } }} @Override Public voidOnDestroy () {Super.ondestroy (); System. out. println ("Service:ondestroy"); }}

Iii. opening and stopping Pollingservice in Mainactivity.java

 Public classMainactivity extends Activity {@Overrideprotected voidonCreate (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 voidOnDestroy () {Super.ondestroy (); //Stop Polling ServiceSystem. out. println ("Stop Polling service ..."); Pollingutils.stoppollingservice ( This, Pollingservice.class, pollingservice.action); }}

Four, the Operation effect

After running the project can see in the console output, every 5s to send a notice, exit activity, the polling service stopped, reached our expectations of the effect, and the lock screen for a long time will not stop the service, because Alarmmanager is the system and services. Demo effects such as:

On the phone we can see the pop-up notification message, click the notification to enter the message interface:

When the message details activity is entered, the message notification on the top status bar is canceled, and the message notification at the top of the status bar can be canceled using the following method:

Notificationmanager manager = (notificationmanager) Getsystemservice (context.notification_service);        Manager.cancelall ();

The above implementation of the use of alarmmanger implementation of a polling method, there are deficiencies or deficiencies of the place to welcome you to add, the above code is only part of the need to project the source of students can go to GitHub clone:https://github.com/tangren03/ Rtpollingdemo

Android Alarmmanager for uninterrupted polling service

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.