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();
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.
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);
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With