多个警报未取消

时间:2015-06-15 11:45:34

标签: android

我正在尝试从警报列表中删除警报,但它没有被取消。我尝试了一切但没有成功。我的代码如下。

MainActivity

private void setAlarm(Calendar targetCal, int id) {

    txtSpeechInput.setText("Alarm set " + targetCal.getTime()+ "");
    intent = new Intent(this, AlarmReceiverActivity.class);
    calendar_alarm.add(targetCal.getTime());
    Utils.setTimetosharedprefernces(targetCal.getTime(),MainActivity.this);

    Log.e("adding id is --", _id+"") ;

    pendingIntent = PendingIntent.getActivity(this,id,intent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}

这是我的取消警报活动

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent stopIntent = new Intent(this,MainActivity.class);
            PendingIntent stopPI = PendingIntent.getBroadcast(MainActivity.mContext, Alarm_id.get(positon),
                    stopIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            flag=true;
            Toast.makeText(getApplicationContext(), "canceleddd", 1000).show();
            stopPI.cancel();
            mgr.cancel(stopPI);
            Alarm_id.remove(positon);
            calendar_alarm.remove(positon);
            deletealarm(positon);
            adapter.notifyDataSetChanged();
}
}

public void deletealarm(int key) {
    getSharedPreferences("Alarms", MODE_PRIVATE).edit()
            .remove("ID" + (key + 1)).apply();
    getSharedPreferences("AlarmsTime", MODE_PRIVATE).edit()
            .remove("THE_DATE" + (key + 1)).apply();
}

1 个答案:

答案 0 :(得分:0)

试用此代码:

这对我有用:

public void cancelAlarm(Context context, int reminderid)
    {
        try
        {
            Intent intentAlarm = new Intent(context, AlarmReceiver.class);
            PendingIntent morningIntent = PendingIntent.getBroadcast(context, reminderid, intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager) (context.getSystemService(Context.ALARM_SERVICE));
            alarmManager.cancel(morningIntent);
            morningIntent.cancel();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

请通过调试确认您的身份。