Broadcast receiver called 2 times when turning off GPS?

ぃ、小莉子 提交于 2021-01-27 05:25:21

问题


Manifest:

<receiver android:name=".GpsLocationReceiver">
    <intent-filter>
        <action android:name="android.location.PROVIDERS_CHANGED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

BroadcastReceiver:

public class GpsLocationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive...");
        if(intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Log.d(TAG, "GPS provider changed...");
            EventBus.getDefault().postLocal(intent.getAction());
        }
    }

}:

回答1:


I faced same problem but I did't find root of problem.It seems device or OS version specific problem.

To know that the message has been called, you could have a static boolean that gets toggled between connect and disconnect and only call your sub-routines when you receive a connection and the boolean is true. Something like:

  private static boolean firstConnect = true;

  @Override
  public void onReceive( Context context, Intent intent )
  {
      //Receive called twice because of device or OS version specific issue.  
      final LocationManager manager = (LocationManager) context.getSystemService( Context.LOCATION_SERVICE );

      if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

          //enable
          if(firstConnect){
              sendStatus("on",context);
              firstConnect=false;
          }

      }else{

          //disable
          if(!firstConnect){
              sendStatus("off",context);
              firstConnect=true;
          }
      }
  }



回答2:


Why not check whether the GPS provider is enabled in your receiver?

lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);


来源:https://stackoverflow.com/questions/31789424/broadcast-receiver-called-2-times-when-turning-off-gps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!