Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fire alarm manager in every 5 min android

Tags:

android

i want to make a service which fire alarm manager in every 5 min interval when my application is running only..so how to do it?

 Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);

  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), sender);
   Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();
like image 570
shyam Avatar asked Oct 07 '11 12:10

shyam


3 Answers

try this:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, pendingIntent);

that alarm will be repeating forever until you cancel it, so you need to cancel it on getting the event when you no longer need it.

like image 67
Vineet Shukla Avatar answered Oct 04 '22 08:10

Vineet Shukla


private class ProgressTimerTask extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // set your time here
                    int currenSeconds = 0
                    fireAlarm(currenSeconds);
                }
            });
        }
    }

Inizialize :

     Timer progressTimer = new Timer();
     ProgressTimerTask   timeTask = new ProgressTimerTask();
     progressTimer.scheduleAtFixedRate(timeTask, 0, 1000);
like image 33
Yahor10 Avatar answered Oct 04 '22 07:10

Yahor10


Cancel the AlarmManager in onPause() of the activity.

A much better solution would be to use a Handler with postDelayed(Runnable r, 5000) since you said only when your application is running. Handlers are much more efficient than using AlarmManager for this.

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable(){
   @Override
   public void run(){
      // code goes here
      myHandler.postDelayed(this, 5000);
   }
}

@Override
public void onCreate(Bundle icicle){
   super.onCreate(icicle);
   // code
   myHandler.postDelayed(myRunnable, 5000);
   // to start instantly can call myHandler.post(myRunnable); instead
   // more code
}

@Override
public void onPause(){
   super.onPause();
   // code
   myHandler.removeCallbacks(myRunnable); // cancels it
   // code
}
like image 33
DeeV Avatar answered Oct 04 '22 06:10

DeeV