【问题标题】:Conflict of id in cancelling multiple alarms in androidandroid中取消多个闹钟的id冲突
【发布时间】:2016-02-01 06:53:24
【问题描述】:

我的应用允许用户设置在特定时间服药的提醒。 设置这些警报没有问题。我很难在稍后在另一个活动中取消这些警报。

这是我设置闹钟的代码:

private void setAlarms() {
    Intent myIntent=new Intent(getApplicationContext(), AlarmReceiver.class);
    myIntent.putExtra("MedName",medication_name);
    myIntent.setAction("b5.project.medibro.receivers.AlarmReceiver");
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


    int counter=0;
    for(String timer: timers){
        //timer is a string of the form "hh:mm"
        try {
            String[] comps=timer.split(":");
            Calendar cal=Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(comps[0]));
            cal.set(Calendar.MINUTE, Integer.valueOf(comps[1]));
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            //Date date= dateFormat.parse(startDate + " " + timer);
            Log.d(TAG,comps[0]+" "+comps[1]+ "Alarm Time: " + cal.getTime().toString());
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), counter, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    cal.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY,
                    pendingIntent);

            Log.d(TAG,"Counter: "+counter);
            counter++;

        } catch (ParseException e) {
            e.printStackTrace();
            Log.d(TAG,"Time Parsing error: "+e.getMessage());
        }
    }

如您所见,计数器是属于 ONE Medicine 的 pendingIntents 的 id。 但是当有多种药物时,待处理的意图将具有相同的 id。(计数器值)

谁能建议一种替代/有效的方法来解决这个冲突?

【问题讨论】:

    标签: android android-intent android-pendingintent android-alarms repeatingalarm


    【解决方案1】:

    当循环结束时,您必须将计数器值保存在某处。并在循环开始时获取它。 将它们保存为以逗号分隔的整数字符串,其中包含 与特定药物相关的所有意图。 例如:

    String a = "0,1,2,3,4";
    putString("MEDICINE_1",a);
    

    然后

    getString("MEDICINE_1").split(',')
    

    【讨论】:

    • 但是“MEDICINE_2”呢?即使它具有相同的计数器值(0,1,2,3,4),我也无法获取正确的待处理意图,因为计数器值会覆盖每个其他
    • 将counter的初始化移出方法。这样计数器值在添加新药时不会从 0 开始。
    猜你喜欢
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多