fire alarm manager in every 5 min 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 = Pe开发者_StackOverflowndingIntent.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
}
Set Alarm repeating every 5 minutes in Kotlin
val intent = Intent(context, OnetimeAlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (1000 * 60 * 5).toLong(), pendingIntent)
To cancel Alarm
val intent = Intent(context, OnetimeAlarmReceiver::class.java)
val sender = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_IMMUTABLE)
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmManager.cancel(sender)
精彩评论