报警管理器调用一个意图服务,在点击按钮后,它应该取消但报警管理器不断触发服务

alarm manager to call an intent service, after on the on click of the button, it should cancel but the alarm manager keeps triggerring the service

按钮在点击时改变,这就是为什么有一个标志。但是警报管理器并没有停止意图,即使在点击取消警报管理器

时它也会永远保持运行
if (flag) {
    flag = false;
    imageButton.setImageResource(R.drawable.mybuttonbc);
    Intent intent = new Intent(HomeActivity.this, IntentServices.class);
    intent.setAction("upload");
    intent.putExtra("lat", lats);
    intent.putExtra("long", longs);

    final PendingIntent pintent = PendingIntent.getService(HomeActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, pintent);
    Snackbar.make(getWindow().getDecorView().getRootView(), "recording started!", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

} else {
    flag = true;
    imagePanicButton.setImageResource(R.drawable.mybuttona);
    Intent intent = new Intent(HomeActivity.this, IntentServices.class);
    final PendingIntent pIntent = PendingIntent.getService(HomeActivity.this, 0, intent,   PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pIntent);
    Snackbar.make(getWindow().getDecorView().getRootView(), "recording stopped!", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}

您缺少最初用于创建警报的 Intent 中的操作。

在取消闹钟的代码中加入这一行即可:

intent.setAction("upload");

所以它看起来像这样:

if (flag) {
    flag = false;
    imageButton.setImageResource(R.drawable.mybuttonbc);
    Intent intent = new Intent(HomeActivity.this, IntentServices.class);
    intent.setAction("upload");
    intent.putExtra("lat", lats);
    intent.putExtra("long", longs);

    final PendingIntent pintent = PendingIntent.getService(HomeActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, pintent);
    Snackbar.make(getWindow().getDecorView().getRootView(), "recording started!", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

} else {
    flag = true;
    imagePanicButton.setImageResource(R.drawable.mybuttona);
    Intent intent = new Intent(HomeActivity.this, IntentServices.class);
    intent.setAction("upload"); // <-Added
    final PendingIntent pIntent = PendingIntent.getService(HomeActivity.this, 0, intent,   PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pIntent);
    Snackbar.make(getWindow().getDecorView().getRootView(), "recording stopped!", Snackbar.LENGTH_LONG)
            .setAction("Action", null).show();

}