2015-10-20 13 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()。 –

相关问题