我如何收到系统广播当GPS状态发生了变化?(How do I receive the system

2019-06-26 04:04发布

我写了下面的代码,但它不工作。 有谁能够帮我? 我只想被动接收GPS状态的变化,而不是主动查询。 节能是最重要的。

没有消息输出。

package com.sharelbs.lbs.service;  
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class GPStStatusReceiver extends BroadcastReceiver {
  public static final String GPS_ENABLED_CHANGE_ACTION = "android.location.GPS_ENABLED_CHANGE";
  @Override
    public void onReceive(Context context, Intent intent) {
      Log.d("---------log--------","GPS Status onReceive");
      if(intent.getAction().equals(GPS_ENABLED_CHANGE_ACTION)){
        Log.d("---------log--------","GPS Status Changed");
        startMyProgram();
      }
    }
}

这里是我的Manifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<receiver android:name=".service.GPStStatusReceiver"> 
  <intent-filter> 
    <action android:name="android.location.GPS_ENABLED_CHANGE" /> 
  </intent-filter> 
</receiver>

Answer 1:

我相信你只是指向清单中的错误的位置,改变接收者的姓名:

<receiver android:name=".GPStStatusReceiver">

这种类型的接收器是伟大的开始,只要是支持GPS的应用程序,但在应用程序运行LocationListener的的onProviderEnabled()或onProviderDisable()将赶上这些即使刷新间隔设置为10天,1000英里更多。 所以,你不一定会浪费电池电源如果你通过大手笔设置的requestLocationUpdates()方法。

此外,从评论

我只能猜测,你是不是收到GPS_ENABLED_CHANGE因为你不是触发位置请求。 只需点击该复选框在位置菜单将不广播这个通知启用GPS功能时,某些应用程序必须要求的当前位置。 另外,我没有找到这个意向,这意味着任何官方文件的Android可能会改变或在任何时间删除此 。

也许你想正式支持LocationManager.PROVIDERS_CHANGED_ACTION ,当GPS提供商(和其他供应商)启用/禁用这将播出的意图。

<action android:name="android.location.PROVIDERS_CHANGED" />


文章来源: How do I receive the system broadcast when GPS status has changed?
标签: android gps