android - 无法停止使用 alarmManager 启动的服务

标签 android service location alarmmanager

我在取消闹钟和启动服务时遇到问题。

我在 Activity 中设置闹钟:

public class AlarmStarter extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      Intent locationPollerIntent = new Intent(this, LocationPoller.class);     
      PendingIntent pendingIntent = PendingIntent.getBroadcast
                (getApplicationContext(), REQUEST_CODE, locationPollerIntent, 0);

      alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
      alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                             SystemClock.elapsedRealtime(), 6000, pendingIntent);
    }
}

LocationPoller intent 将启动一个服务来获取设备的位置。 所以我使用 alarmManager 以特定频率重复此搜索。

之后,当我在 BroadcastReceiver 上获得我的位置时,我调用另一个 Activity 来显示位置并发出通知。

此时,我想停止搜索位置。 所以我尝试取消alarmManager。

public class Notifier extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_notifier);

        findViewById(R.id.btTurnOffAlarm).
                               setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intentToStop = new Intent(this, LocationPoller.class);
                PendingIntent pendingIntentToStop = PendingIntent.getBroadcast 
                       (getApplicationContext(), REQUEST_CODE, intentToStop, 0);

                AlarmManager alarmManager = (AlarmManager)
                                getSystemService(ALARM_SERVICE);
                alarmManager.cancel(pendingIntentToStop);
            }
        });
    }
}

但这不起作用,它继续搜索位置。

有什么线索吗?

谢谢。

最佳答案

您必须使 Intent 独一无二。

类似于:

locationPollerIntent.setData((Uri.parse("YOUR UNIQUE ID FOR THIS INTENT")));

AlarmManager 会在为您返回正确的警报时检查 Intent 的数据字段。 只需为 Intent 的数据设置一个唯一的 Uri。

因此,当您取回闹钟时,请执行以下操作:

intentToStop.setData((Uri.parse("YOUR SAME UNIQUE ID FOR THIS INTENT")));

警报应在之后取消。

关于android - 无法停止使用 alarmManager 启动的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605685/

相关文章:

android - map fragment 的中心位置 - Android 谷歌地图

android - 如何在 Dagger 2.10 中创建自定义作用域模块

android - Android 中的文本样式

Android 4.4 中断 jquery on(touchstart/touchmove/touchend)?

c# - 在 Windows 服务器上安装 C# 服务(拒绝访问)

linux - 如何检查 JBoss 是否在 Unix 服务器上运行?

iphone - iPhone 应用程序可以在后台因重大位置变化而唤醒进行网络事件吗?

android - UsbHost 模式下的 TransactionTooLargeException

wcf - 在 Windows 服务中托管 WCF 服务

Android:如何获取手机网络提供商位置