报警待定意图一次又一次地被调用

时间:2017-11-07 05:55:34

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

我在我正在处理的项目中添加了警报。他们在我所有的条件下工作正常。面对一个小问题。我已经添加了一次性警报,我希望它按时启动,这是正常工作,并且在达到它的时间时它正在打开一个我通过意图发送的值的活动。问题是甚至在警报被触发后,再次调用挂起的意图并且当我关闭该活动时它会打开具有空值的活动它再次弹出我关闭它的次数。待处理的意图在指定时间被​​解雇后不会被取消。下面是我设置闹钟的代码。

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);
        }
    }

1 个答案:

答案 0 :(得分:0)

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