关闭GPS时,广播接收器会被调用两次?

6

清单:

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

}:

Log.d(TAG, "onReceive..."); 编辑为 Log.d(TAG, intent.getAction();,以查看为什么会调用两次 :) - Skizo-ozᴉʞS ツ
两次相同:android.location.PROVIDERS_CHANGED - powder366
3个回答

4

我曾经遇到过同样的问题,但是没有找到问题的根源。看起来这是与设备或操作系统版本有关的问题。

要知道消息是否已被调用,您可以使用一个静态布尔值,在连接和断开连接之间进行切换,并在接收连接并且布尔值为真时才调用您的子程序。类似以下内容:

  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

这是我的解决方案代码

public class MyBroadcastReceivers extends BroadcastReceiver {

    static boolean isGpsEnabled,isPermissionAskedOnce=true;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION)) {
            LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
            isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            

            if(isGpsEnabled){
                   //do you stuff
                    isPermissionAskedOnce=true;
            }else{
                 
                if(isPermissionAskedOnce){
                  //do your stuff 
                    isPermissionAskedOnce=false;
                }
            }
        }
    }


}

你的回答可以通过提供支持信息来改进。请编辑以添加更多详细信息,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

-1

为什么不检查一下接收器中的GPS提供程序是否已启用?

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

在 onReceive 中不应该有耗时的调用。我通过 EventBus 发送了一个事件,现在它被发送了两次。在事件接收器中,我有你提供的代码。但它仍然没有回答我的问题... - powder366

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接