【问题标题】:Alarm pending intent getting called again and again警报未决意图一次又一次地被调用
【发布时间】:2017-11-07 05:55:33
【问题描述】:

我在我目前正在进行的项目中添加了警报。他们在我所有的条件下都工作得很好。面临一个小问题。我添加了一个一次性警报,我希望它按时触发,它工作正常,并且在达到它的时间时,它正在打开一个带有我通过意图发送的值的活动。问题是即使在触发警报之后,挂起的意图也会再次被调用,并且当我关闭该活动时它会以空值打开活动,它再次弹出的次数与我关闭它的次数一样多。待定意图在其指定时间触发后不会被取消。下面是我设置闹钟的代码。

public void setAlarm(int hours, int minutes,String AMPM, String alarmType,String message, String extraMessage)
    {

        Random rand = new Random();
        int  n = rand.nextInt(10000) + 1;
        Log.e("HMA",hours+"   "+minutes+"   "+AMPM + " " + message + extraMessage);

//                       Toast.makeText(getApplicationContext(), "Alarm On",
        //   Toast.LENGTH_SHORT).show();
        Calendar calendar = Calendar.getInstance();
        // set selected time from timepicker to calendar
        calendar.set(Calendar.HOUR_OF_DAY, hours);
        calendar.set(Calendar.MINUTE,minutes);
        calendar.set(Calendar.SECOND,00);


        if(AMPM.equals("PM")) {
            Log.e("PM","");
            calendar.set(Calendar.AM_PM, Calendar.PM);
        }
        else
        {
            calendar.set(Calendar.AM_PM, Calendar.AM);
        }
        Intent myIntent = new Intent(this,
                MyReceiver.class);
        AlarmManager alarmManager;
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        myIntent.putExtra("alarmType",alarmType);
        myIntent.putExtra("gifMessage",message);
        myIntent.putExtra("extraMessage",extraMessage);


        PendingIntent pendingIntent;

        // A PendingIntent specifies an action to take in the
        // future
        pendingIntent = PendingIntent.getBroadcast(
                this, n, myIntent, 0);

        // set alarm time
        if(Build.VERSION.SDK_INT<19) {
            alarmManager.set(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
        else if(Build.VERSION.SDK_INT>=19 && Build.VERSION.SDK_INT<=22)
        {
            alarmManager.setExact(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
        else if(Build.VERSION.SDK_INT>=23)
        {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC,
                    calendar.getTimeInMillis(), pendingIntent);
        }
    }

【问题讨论】:

  • 发布你的错误信息以及这个类的完整代码

标签: android alarmmanager android-pendingintent android-alarms android-broadcastreceiver


【解决方案1】:

我使用 IntentService 而不是 Service 解决了这个问题,并在 onStartCommand 中返回 START_NOT_STICKY。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2018-08-20
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多