其他分享
首页 > 其他分享> > android-无法停止使用alarmManager启动的服务

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

之后应取消警报.

标签:location,alarmmanager,android,service
来源: https://codeday.me/bug/20191102/1989259.html