我想在我的应用程序运行时每5分钟启动一次火警管理器服务。那该怎么办?
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();
答案 0 :(得分:8)
试试这个:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, pendingIntent);
该警报会一直重复,直到你取消它为止,因此你需要在不再需要它时取消它。
答案 1 :(得分:2)
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);
}
});
}
}
初始化:
Timer progressTimer = new Timer();
ProgressTimerTask timeTask = new ProgressTimerTask();
progressTimer.scheduleAtFixedRate(timeTask, 0, 1000);
答案 2 :(得分:2)
取消活动AlarmManager
中的onPause()
。
更好的解决方案是将Handler
与postDelayed(Runnable r, 5000)
一起使用,因为您只在应用程序运行时才说过。 Handlers
比使用AlarmManager
效率更高。
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
}