如何从被调用的服务访问pendingIntent变量

时间:2015-10-20 12:40:08

标签: android service alarmmanager android-pendingintent

AlarmManager的代码

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 个答案:

答案 0 :(得分:1)

PendingIntent只需要"匹配"。您可以通过相同的方式设置它来完成您尝试做的事情。您希望将specialCode转换为常量,或者在Integer中没有值的情况下定义ids.xml,并让系统在编译期间分配值。通过后者,您可以保证它将是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>