Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Broadcast receiver called 2 times when turning off GPS?

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

}:
like image 229
powder366 Avatar asked Oct 31 '22 22:10

powder366


1 Answers

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;
          }
      }
  }
like image 145
Harshal Avatar answered Nov 11 '22 21:11

Harshal