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 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 = 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 context, Class <?> Cls, String action) {AlarmManager manager = (AlarmManager) context. getSystemService (Context. ALARM_SERVICE); Intent intent = new Intent (context, cls); intent. setAction (action); PendingIntent pendingIntent = PendingIntent. getService (context, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT); // cancels the service manager being executed. cancel (pendingIntent );}}
Public class PollingService extends Service {public static final String ACTION = "com. ryantang. service. pollingService "; private Notification mNotification; private icationicationmanager mManager; @ Overridepublic IBinder onBind (Intent intent) {return null ;}@ Overridepublic void onCreate () {initNotifiManager ();} @ Overridepublic void onStart (Intent 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 = 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 ");}}
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);}}

 

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.