【发布时间】:2015-10-11 19:54:15
【问题描述】:
为什么BroadcastReceiver 被多次触发。
我的示例项目如下代码
安卓清单
<receiver
android:name=".LocationProvideListener"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED"/>
</intent-filter>
</receiver>
广播接收器
public class LocationProvideListener extends BroadcastReceiver {
private static final String TAG = "LocationProvideListener";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION))
{
// react on GPS provider change action
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isNetwork = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean isGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.e(TAG, "IsNetwork = " + (isNetwork ? "true" : "false"));
Log.e(TAG, "IsGPS = " + (isGPS ? "true" : "false"));
}
}
}
记录(打开位置时)
07-22 12:09:47.275 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = false
07-22 12:09:47.275 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = true
07-22 12:09:47.778 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = false
07-22 12:09:47.778 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = true
07-22 12:09:48.115 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = false
07-22 12:09:48.115 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = true
日志(接受许可时)
07-22 12:09:55.412 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = true
07-22 12:09:55.412 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = true
记录(关闭位置时)
07-22 12:10:04.856 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = false
07-22 12:10:04.856 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = false
07-22 12:10:04.941 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsNetwork = false
07-22 12:10:04.941 22176-22176/com.example.checkLocationProvider E/LocationProvideListener﹕ IsGPS = false
【问题讨论】:
-
不,我不考虑它的行为,但我尝试根据我的业务逻辑解决它。另外,我已经实现了一些融合位置 api 的包装库,您可以在此处查看我的示例项目 github.com/sattha/Jongz-FusedLocationAPI
-
对我来说同样的问题,涉及 android.location.PROVIDERS_CHANGED 的两次接收。