Search code examples
androidalarmmanager

What to use: AlarmManger or my own service with Timer (scheduleAtFixedRate(task, delay, period));



in my case i have to do a task lets say every 5 min in next 3hour. Which one would be better AlarmManger or Timer. In case of AlarmManger i will be starting an intent service which will do the task and in later one i will use TimerTask. Moreover how will get pending intent to use AlarmManager.cancel(pendingIntent) in intentService onHandleIntent.

possible copy of this, but have different scenario. Timer Task VS Alarm Manager usage in Android Service

Thanks.


Solution

  • First, set up:

    Intent i = new Intent( context.getApplicationContext(), NameOfYourClass.class );
    PendingIntent pi = PendingIntent.getBroadcast( c.getApplicationContext(), 0, i, 0 );
    AlarmManager am = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE );
    am.setRepeating( AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5*60*1000, pi ); 
    // ELAPSED_REALTIME will execute ONLY when phone is awake, to execute always use ELAPSED_REALTIME_WAKEUP
    

    Just after this initial setup save when counter started: , ex. PreferenceManager

    Finally, when the time comes:

    Intent i = new Intent( context.getApplicationContext(), NameOfYourClass.class );
    PendingIntent pi = PendingIntent.getBroadcast( context.getApplicationContext(), 0, i, 0 );
    AlarmManager am = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE );
    am.cancel( pi );