LocationManager:查明是否启用了某个侦听器

时间:2014-04-06 04:45:17

标签: android locationmanager

有没有办法知道是否启用了监听器?

LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListenerGPS);

现在听众接收到GPS更新并且GPS已开启。

调试时我可以看到mlocManager.mListeners,它是一个HashMap,第一个条目是我的监听器。

删除侦听器将清除列表。:

mlocManager.removeUpdates(mlocListenerGPS);

我需要一种方法来确定监听器是否处于活动状态或已被删除。

我需要像

这样的东西
boolean enabled = mlocManager.mListeners.size() > 0; // assuming I only use one listener

任何想法(除了在开关上使用标志)?

2 个答案:

答案 0 :(得分:1)

让您的倾听者作为一项服务工作。现在使用以下方法检查您的服务是否正在运行。

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
    if (MyService.class.getName().equals(service.service.getClassName())) {
        return true;
    }
}
return false;
}

答案 1 :(得分:-1)

让我建议另一种方法。

您可以:

,而不是检查LocationListener是否正在运行
  1. 创建一个名为LocationListener的{​​{1}}类或您想要的任何名称。

  2. 使用以下命令激活服务LocalLocationListener方法中的LocationListener

    this.mLocalLocationListener = new LocalLocationListener(this);

  3. 在服务的onStartCommand方法中,停止onDestroy()课程:

    mLocationManager.removeUpdates(this.mLocalLocationListener);

  4. 最后,提供一个首选项选项,允许您的用户选择更新从LocationListener类返回的信息的频率。这是一项重要功能,可让您的用户节省电池电量:

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,mlocListenerGPS);

    会消耗大量电力,因为它不断要求提供信息 GPS提供商。读 here 了解更多信息。

相关问题