2012-09-26 42 views
2

我爲我的計時器使用AlarmManager。我有2個班。Android AlarmManager不斷關閉

在第一類中(MainActivity)我開始我的報警與下面的代碼:

public void startAlarm(long Seconds) { 
    Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class); 
    pendingIntent = PendingIntent.getService(MainActivity.this, 13141337, 
      myIntent, 0); 
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTimeInMillis(System.currentTimeMillis()); 
    calendar.add(Calendar.SECOND, (int) Seconds); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 
      pendingIntent); 
} 

在另一大類(AlarmSound),其中警報響起和手機振動,我打電話給我的取消報警方式。

public void stopAlarm(){ 
    Intent intentstop = new Intent(AlarmSound.this, MyAlarmService.class); 
    PendingIntent senderstop = PendingIntent.getBroadcast(AlarmSound.this, 
      13141337, intentstop, 0); 
    AlarmManager myalarm = (AlarmManager) getSystemService(ALARM_SERVICE); 
    myalarm.cancel(senderstop); 
    Log.w("Karl","stopAlarm?"); 
} 

這是正確的方法嗎?因爲我的鬧鐘在android 4.1上不斷消失。

在此先感謝!

回答

1

您的取消不工作。待定的意圖必須匹配 - 因爲它們具有不同的上下文(MainActivity和AlarmSound),所以這個取消不會起作用。你也必須同時使用getService。 您可以

一)嘗試重新建立一個匹配未決的意圖

B)得到的是,在服務開始服務的的PendingIntent,並用它來取消

但通常每警報剛剛熄滅一次,如果你不使用setRepeating()。

你確定你正在用stopself()正確終止你的服務並且在onStartCommand()方法中給它正確的標誌嗎?

+0

謝謝你的回答,我不使用setRepeating是一個問題?我只使用上面的代碼來啓動我的鬧鐘。我也不使用stopself和onStartCommand。我想我正確地終止了?我如何確定這一點?我的MainActivity中有另一個stopAlarm方法,效果很好。我確信(通過測試等)如何在AlarmSound中使用stopAlarm? –

+0

可以請您發佈完整的AlarmSound代碼嗎? –

+0

我使用了pastebin,因爲我無法回答自己的代碼,http://pastebin.com/cnxY8mH5你去了 –