开发者

android : remove all alarm when on onDeleted() for AppWidgetProvider

I'm working on a widget that set repeating alarms to refresh.

To set these repeating alarms, in the configuration Activity, in an OnClickListener(), I do :

        Intent widgetUpdate = new Intent();
        widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,mAppWidgetId);
        widgetUpdate.setData(Uri.withAppendedPath(Uri.parse("wd_widget://widget/id/"), String.valueOf(mAppWidgetId)));

        PendingIntent newPending = PendingIntent.getBroadcast(context, 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

        int mins = 60;
        alarms.cancel(newPending);
        alarms.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),  mins*1000*60,newPending);

And my AppwidgetProvider receive this intent in onReceive(), and refresh the view :

if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) {
            Bundle extras = intent.getExtras();
            if(extras!=null) {
                int widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
                updateAppWidget(context, AppWidgetManager.getInstance(context), widgetId);
            }

My problem : When I kill the Widget, Alarm stay active althought I do in onDeleted() of AppwidgetProvider:

Intent widgetUpdate = new Intent();
    widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    PendingIntent newPending = PendingIntent.getBroadcast(context, 0, widgetUpdate, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    for (int开发者_运维知识库 appWidgetId : appWidgetIds) {      
        Log.i("DEBUG","Removing Alarms");
        alarms.cancel(newPending);
    }

So how to kill all the alarm when leaving the widget ? Best, Christophe.


I think you need to send the same intent to cancel the alarm, i.e. in onDeleted, you are not sending the appWidgetId.


When creating the PendingIntent, use a non-zero value for the "request code". The documentation says it is not used, but in my app I had to set this value. When cancelling the alarm, I use the same value to clear the alarm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜