Broadcast receiver called 2 times when GPS is turned off?

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());
        }
    }

}:

      

+3


source to share


2 answers


I had the same problem, but I couldn't find the root of the problem. Seems to be a problem with specific device or OS version.

To find out that a message has been called, you can have a static boolean that switches between connect and disconnect and calls subroutines when a connection is received, 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;
          }
      }
  }

      

+1


source


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



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

      

-1


source







All Articles