我已将此BroadcastReceiver
用作GPS状态接收器,以监视用户何时在顶部导航菜单中打开/关闭其位置。它在两周前突然停止工作(未调用整个接收器onReceive()
方法)(可能与Android 10版本有关)。您知道什么地方可能出问题吗?
以前效果很好。
class GPSReceiver: BroadcastReceiver(){
companion object{
const val GPS_PAYLOAD = "gps_payload"
const val GPS_STATE = "gps_state"
}
override fun onReceive(context: Context, intent: Intent) {
App.log("IsGPSEnabled: callingonReceive")
val action = intent.action
if(action != null && action == LocationManager.PROVIDERS_CHANGED_ACTION){
try {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val int = Intent(GPS_PAYLOAD)
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
int.putExtra(GPS_STATE, true)
} else {
int.putExtra(GPS_STATE, false)
}
LocalBroadcastManager.getInstance(context).sendBroadcast(int)
} catch (ex: Exception) {
App.log("IsGPSEnabled: $ex")
}
}
}
}
AndroidManifest:
<!-- GPS status receiver -->
<receiver android:name=".services.GPSReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Android 8.0+清单接收器已过时
在活动中注册对象BroadcastReceiver监视意图:
registerReceiver(gpsStatusReceiver, IntentFilter("android.location.PROVIDERS_CHANGED"))
您必须像这样更新您的xml部分:
<receiver
android:name=".Util.GpsReceiver"
android:enabled="true"> <!-- do this and try again -->
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
不要忘记此权限:
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>