2011-10-07 50 views
3

我想在每个5分钟的时间间隔内制作一个服务,当我的应用程序运行时,火灾报警管理器只有..那么该怎么做?火灾报警管理器每5分钟一次android

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(); 
+1

为什么你需要一个服务?您不需要一项服务,只需每5分钟发出一次警报。 –

回答

7

试试这个:

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

该警报将永远重复,直到你取消它,所以你需要取消它越来越事件当你不再需要它。

+1

如何停止正在运行的服务?当我退出应用程序 – shyam

+0

时使用stopService().....您是否收到任何错误? –

+0

工作正常....感谢 – shyam

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); 
       } 
      }); 
     } 
    } 

Inizialize:

 Timer progressTimer = new Timer(); 
    ProgressTimerTask timeTask = new ProgressTimerTask(); 
    progressTimer.scheduleAtFixedRate(timeTask, 0, 1000); 
+0

不会在服务工作检查这个http://stackoverflow.com/questions/14924295/service-of-an-app-stops-when-phone-is-not-being-charged为什么 – HiB

+1

它不工作,当你手机处于睡眠模式。 – Yahor10

2

取消该活动的AlarmManageronPause()

更好的解决方案是将HandlerpostDelayed(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 
} 
+0

不会在服务中工作,请检查此问题http://stackoverflow.com/questions/14924295/service-of-an-app-stops-when-phone-is-not-being-charged)原因 – HiB

+1

这并不意味着要在服务中运行。他只是在应用程序正在运行时才询问如何每5分钟打一次**。正如其他答案所说的那样,启动一项服务本来就是过分的。 – DeeV