【问题标题】:Kotlin - BroadCast Receiver calling IssueKotlin - 广播接收器调用问题
【发布时间】:2020-05-07 05:49:23
【问题描述】:

我这里有小问题。

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

我创建了如下的广播接收器:

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


    【解决方案1】:

    您是在 Oreo 或更高版本上运行此程序吗?如果是这种情况,这将不起作用,因为 android 限制了隐式 broastcastreceivers。 https://developer.android.com/about/versions/oreo/background.html#broadcasts

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

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

    您在 register 中创建 instanceA 并在 unregister 中取消注册一个甚至没有注册的新实例。

    mContext.unregisterReceiver(GpsLocationReceiver())
    

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

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

    【讨论】:

    • 那我怎么知道 GPS 正在开启呢?
    • 你会知道的,目前你通过两种方式注册接收者,隐式和显式。通过从清单中删除,您将仅依赖于显式注册。在 android O 之后,框架不允许开发者通过 manifest 文件注册广播接收器。我们必须通过 register() 和 unregister() 调用来做到这一点。
    【解决方案2】:

    来自文档:

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

    根据我的经验,只有在位置发生变化时才会更新位置广播。这样做是为了优化设备的电池寿命。

    【讨论】:

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