【问题标题】:GPS Status receiver stopped working 2 weeks agoGPS 状态接收器在 2 周前停止工作
【发布时间】:2020-02-04 12:43:12
【问题描述】:

我使用这个BroadcastReceiver 作为 GPS 状态接收器来监控用户何时打开/关闭顶部导航菜单中的位置。它在 2 周前突然停止工作(整个接收器 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+ 清单接收器已过时

在Activity中注册对象BroadcastReceiver监控意图:

registerReceiver(gpsStatusReceiver, IntentFilter("android.location.PROVIDERS_CHANGED"))

【问题讨论】:

  • 根据您的问题,我知道您需要在 GPS 开启/关闭时执行一些操作??
  • 是的,这是正确的。
  • 可能与 developer.android.com/about/versions/oreo/… 相关文档列出了可能的替代方案,例如在应用程序运行但在“后台”时侦听位置状态的前台服务

标签: android kotlin broadcastreceiver android-permissions android-gps


【解决方案1】:

你必须像这样更新你的 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"/>

【讨论】:

    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多