检测位置设置何时可用(例如:记录其使用时间等)?

问题描述 投票:-2回答:1

Android-Oreo基本上打破了我的应用程序,让我在水中死了.. 我的目标:在后台运行,并在“位置”设置打开时做出反应。 我不需要实际使用位置 - 我只需要检测它何时可用。 (不幸的是,从Android-O开始,我不能再使用providers_changed intent过滤器来执行此操作)。 我该怎么做呢?建议将不胜感激!

android broadcastreceiver android-service android-8.0-oreo android-location
1个回答
0
投票

解: 动态注册你的BroadcastReceiver(从你的代码中),而不是从Manifest注册。而且,你应该使用android.location.PROVIDERS_CHANGED(当然导入LocationManager.PROVIDERS_CHANGED_ACTION),而不是检查硬编码的正则表达式LocationManager。 例:

public void buttonClick(View view) {

    IntentFilter filter = new IntentFilter();
    filter.addAction("android.location.PROVIDERS_CHANGED");

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches(LocationManager.PROVIDERS_CHANGED_ACTION)) {
                Log.i(TAG, "Action MATCHES LocationManager.PROVIDERS_CHANGED_ACTION!");
            }
        }
    };

    this.getApplicationContext().registerReceiver(receiver, filter);
    Log.i(TAG, "RECEIVER HAS BEEN REGISTERED");

}

请记住在代码中正确注销接收器,因为即使用户按下后退按钮或主页按钮,它也会在后台继续运行。它将停止接收的唯一时间是用户从多任务按钮中杀死它,或强制停止接收。

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