Kotlin-BroadCast接收方呼叫问题

问题描述 投票:0回答:2

我在这里有小问题。

我已经从用户那里获得了所有必要的位置权限。

我已经如下创建广播接收器:

public class GpsLocationReceiver : BroadcastReceiver() {
    private lateinit var mLocationManager: LocationManager
    override fun onReceive(context: Context, intent: Intent) {
        LogUtil.e(">>>On Receive","called")
        mLocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            LogUtil.e(">>>On Receive","called inside")
            GetLocationAccessFragment().getAndSaveCurrentLocation()
        }
    }
}

在我的清单中,我已完成以下操作:

<receiver android:name=".ui.user_profile.fragments.GetLocationAccessFragment$GpsLocationReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

现在,要在我的片段init()方法中注册它:

mContext.registerReceiver(
            GpsLocationReceiver(),
            IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)

并且在工作完成后取消注册:

mContext.unregisterReceiver(GpsLocationReceiver())

但是,不幸的是,当我在设备中打开/关闭GPS时,未调用OnReceive()方法。可能是什么问题?

android kotlin gps provider android-gps
2个回答
0
投票

您是在Oreo还是更高版本上运行此程序。如果真是这样,这将无法工作,因为android限制了隐式broastcastreceivers。https://developer.android.com/about/versions/oreo/background.html#broadcasts

使用显式广播。另一个问题是

mContext.registerReceiver(
        GpsLocationReceiver(),
        IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION)

您正在注册中创建instanceA,并在尚未注册的未注册状态中注销一个新实例。

mContext.unregisterReceiver(GpsLocationReceiver())

在两个调用中使用相同的实例。

当您使用显式广播注册时,不需要清单进行声明。希望这会有所帮助。


0
投票

从文档:

可能需要一段时间才能收到第一次位置更新。如果需要立即定位,则应用程序可以使用getLastKnownLocation(java.lang.String)方法。

根据我的经验,仅当位置更改时,位置广播更新才会出现。这样做是为了优化设备的电池寿命。

© www.soinside.com 2019 - 2024. All rights reserved.