2015-02-05 36 views
0

檢查AlarmIntent我創建重複報警從不同的活動

 Intent intent = new Intent(StartActivity.this, NotificationService.class); 
     intent.setAction(NotificationService.ACTION_PULL_NOTIFICATION); 
     PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0); 
     AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), updateFrequency * 1000, pintent); 

這個工程作爲迄今爲止預期。我檢查我的報警是否與此有關

Intent intent = new Intent(StartActivity.this, NotificationService.class); 
    intent.setAction(NotificationService.ACTION_PULL_NOTIFICATION); 
    return (PendingIntent.getBroadcast(getApplicationContext(), ALARM_ID, 
      intent, 
      PendingIntent.FLAG_NO_CREATE) != null); 

這工作正常。當我需要檢查是否從其他活動(我的情況是SettingsActivity)設置了警報時,會出現問題。

我無法檢查使用第二功能,因爲SettingsActivity有「StartActivity.this」無法訪問,所以我不能創建相同的意圖。

這應該是簡單的東西,我希望我錯過了什麼,但我想設置的意圖,所以我可以檢查它的報警在不同的活動,但至今沒有得到地方的多種方式。我找到了這個答案:Android How to stop AlarmManager in other Activity但它對我也不起作用。

有沒有辦法做到這一點?

TL; DR:在活動A上創建報警,需要檢查它是否在活動B.積極

+0

嘗試使用共享偏好。對於e.x.更新一個true然後檢查布爾值的地方(在任何活動)你想 – Amsheer 2015-02-05 14:28:50

+0

謝謝,這是一個好主意。不幸的是這並沒有解決我的問題,因爲我也需要能夠取消從SettingsActivity報警,我不能肯定,用戶將在SettingsActivity禁用報警後,導航回StartActivity。 – 2015-02-05 14:30:57

+0

我在Android的AlarmManager系統上稍微有些惱火。能有多難是添加和檢索基於一個獨特的報警標識標籤,而不是這個「需要精確,同樣意圖」廢話報警?這看起來對我來說是一種嚴重缺乏遠見的。 – 2015-02-05 14:47:52

回答

1

我解決它通過使用此代碼:

public static boolean isNotificationAlarmSet(Context context, int alarmId){ 
    Intent intent = new Intent(context, NotificationService.class); 
    intent.setAction(NotificationService.ACTION_PULL_NOTIFICATION); 
    return (PendingIntent.getService(context, alarmId, intent, PendingIntent.FLAG_NO_CREATE) != null); 
} 

public static void setNotificationAlarm(Context context, int alarmId, int frequency) { 
    Intent intent = new Intent(context, NotificationService.class); 
    intent.setAction(NotificationService.ACTION_PULL_NOTIFICATION); 
    PendingIntent pintent = PendingIntent.getService(context, alarmId, intent, 0); 
    AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), frequency, pintent); 
} 

public static void removeNotificationAlarm(Context context, int alarmId) { 
    AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    Intent intent = new Intent(context, NotificationService.class); 
    intent.setAction(NotificationService.ACTION_PULL_NOTIFICATION); 
    PendingIntent p = PendingIntent.getService(context, alarmId, intent, 0); 
    if (p != null) { 
     alarm.cancel(p); 
     p.cancel(); 
    } 
} 

我發現提供的上下文並不重要,你可以使用getApplicationContext();