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

我在取消警报和启动服务时遇到问题.

我将警报设置为活动:

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意图将启动服务以获取设备的位置.
因此,我使用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);
            }
        });
    }
}

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

有什么线索吗?

谢谢.

解决方法:

您必须使意图独特.

类似于:

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

当为您找回正确的警报时,AlarmManager将检查意图的数据字段.
只需为意图数据设置唯一的Uri.

因此,当您收到警报时,请执行以下操作:

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

之后应取消警报.

上一篇:1029 旧键盘 (20分)


下一篇:android-保持服务苏醒而不会耗尽电池