2015-10-20 15 views
0

我對AlarmManager代碼:如何從所謂的服務訪問到的PendingIntent變量

Intent intent = new Intent(context, MyService.class); 
PendingIntent pendingIntent = PendingIntent.getService(context, specialCode, intent, 0); 
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, operation); 

我想訪問來自MyService.java的pendingIntent變量停止重複AlarmManager

怎麼可以?

MyService.java

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    if(condition){ 
     PendingIntent pendingIntent = what?//to access same pendingIntent 
     G.alarmManager.cancel(pendingIntent); 
    } 
    return super.onStartCommand(intent, flags, startId); 
} 

回答

1

PendingIntent只需要 「匹配」。你可以通過同樣的方式完成你想要做的事情。您將要將specialCode轉換爲常量或在ids.xml中定義沒有值的Integer,並讓系統在編譯期間分配一個值。通過做後者,你可以保證它是100%獨一無二的。如果您選擇使用生成的ID,那麼您將使用this.getResources().getInteger(R.id.my_alarm)代替specialCode

PendingIntent pendingIntent = PendingIntent.getService(this, specialCode, intent, 0); 
    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); 
    alarmManager.cancel(pendingIntent); 

Android ids.xml Docs

<resources> 
    <item name="my_alarm" type="id"/> 
</resources> 
+0

我想通過'pendingIntent'變量來取消它 當我們把額外給意圖,的PendingIntent尚未 – Simon

+0

定義。如比爾解釋,你並不需要通過對'服務'的'PendingIntent'的引用。您的服務只需要使用與設置警報時使用的參數相同的參數調用PendingIntent.getService()。 –

相關問題