取消PendingIntent |代码没有效果

时间:2015-07-29 17:48:48

标签: java android

尝试使用PendingIntent禁用闹钟。但是代码似乎没有任何错误,但它不起作用。这就是我所做的。

从一个活动开始我发出警报:

private void setAlarm(Calendar targetCal)
{
    Intent alarmintent = new Intent(AddAlarm.this, AlarmReceiver.class);
    alarmintent.putExtra("ALARM_NO", tempx);
    alarmintent.setAction("my.action.string");
    PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, pen, alarmintent, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);


}

从另一个活动我试图杀死警报,但这样做不会产生所需的输出,而是在设定的时间播放警报。 这是代码:

public void alarmSet1(View view)
{

    int a1=1;
    int idTime = (int) System.currentTimeMillis();
    Log.w("myApp", "SAVED VALUE IS:"+idTime);



    if (((ToggleButton) view).isChecked()) {
        Intent intent = new Intent(MainActivity.this, AddAlarm.class);
        intent.putExtra("pendInt", idTime);
        intent.putExtra("tts", a1);
        startActivity(intent);
    }

    else
    {


        SharedPreferences sa = getSharedPreferences("TimesList", Context.MODE_PRIVATE);
        int rec = sa.getInt("ID1",0);
        Log.w("myApp", "RECEIVED VALUE IS:"+rec);


        Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
                rec, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        pendingIntent.cancel();
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pendingIntent);

    }
}

任何修复/解决方案都将受到高度赞赏:)

1 个答案:

答案 0 :(得分:3)

您不需要拨打pendingIntent.cancel(),只需要`alarmManager.cancel(pendingIntnet);'

当您删除闹钟并进行myIntent时,请在制作pendingIntent之前致电myIntent.setAction("my.action.string")