问题
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