关闭GPS时,广播接收机被叫2次? [英] Broadcast receiver called 2 times when turning off GPS?

查看:86
本文介绍了关闭GPS时,广播接收机被叫2次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

清单:

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

BroadcastReceiver:

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

}:

推荐答案

我遇到了同样的问题,但没有找到问题的根源.这似乎是设备或操作系统版本所特有的问题.

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

要知道消息已被调用,您可以有一个在连接和断开连接之间切换的静态布尔值,并且仅在收到连接且布尔值为true时才调用子例程.像这样:

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

这篇关于关闭GPS时,广播接收机被叫2次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆