0


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.

Community
  • 1
  • 1
Awais
  • 222
  • 3
  • 14

1 Answers1

1

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 );
meeDamian
  • 1,143
  • 2
  • 11
  • 24
  • hi thanks it worked, just one thing that if you plan to use intentservice the before am.setRepeating use PendingIntent.getService() instead of getbroadcast. Thanks – Awais Aug 09 '12 at 12:06