android - 监控 GPS 状态(如果用户使用通知栏关闭 GPS 则无法检查)

标签 android android-location

在我的应用中,我需要监控 GPS 状态,应用只能在 GPS 开启的情况下运行,如果用户关闭 GPS,我会显示“位置和安全”设置。我已经为 GPS 监控实现了自定义类:

public class GPSManager {
    LocationManager mLocationManager;
    StatusListener statusListener;


    /**
     * @param Context context - context to get LocationManager service
     * @param IGpsStatusClient client -component, which wants to receive GPS status update
     */
    public GPSManager(Context context, IGpsStatusClient client) {
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        statusListener=new StatusListener(client);
    }

    public boolean isGpsEnabled(){
        return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public void registerUpdates() {
        mLocationManager.addGpsStatusListener(statusListener);
    }

    public void unregisterUpdates() {
       mLocationManager.removeGpsStatusListener(statusListener);
    }

    class StatusListener implements GpsStatus.Listener {

        IGpsStatusClient client;

        public StatusListener(IGpsStatusClient client){
            this.client=client;
        }

        public void onGpsStatusChanged(int event) {
            if(event==GpsStatus.GPS_EVENT_STOPPED){
                client.promptGpsSettings();
            }
        }
    }

}

这里的Client是一个Fragment类的实例。它使用一种方法(我在其中显示位置设置)实现 IGpsStatusClient 接口(interface)。 我在 onResume() 中注册更新并在 onPause() 中注销 但这没有效果。当我展开通知栏并关闭 GPS 然后返回应用程序时,没有显示任何提示。据我了解,GPS 状态通知不像一个“未决 Intent ”,它会挂起一段时间,以便所有接收者都可以处理它。 有什么选择? 据我了解,GPS 只能由用户关闭,不能在我的 Activity 可见时关闭。因此,我只应在 Activity(或 Fragment)生命周期事件中检查 GPS 状态。但是当通知栏展开时,我没有收到 onResume() 或 onPause() 调用(但为什么我没有收到 GPS 状态通知?) 我在考虑服务,但认为这对我的问题来说很昂贵。 有什么帮助吗? 谢谢。

最佳答案

您是否尝试过实现 LocationListener 并使用 onProviderDisabled/onProviderEnabled 方法?

Here是关于 LocationListener

的 android 开发者页面的链接

关于android - 监控 GPS 状态(如果用户使用通知栏关闭 GPS 则无法检查),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7807892/

相关文章:

java - 跨 session /设备处理应用内购买/消耗品?

java - 新项目的公司域名错误

android - 使用 Laravel 和移动客户端(iOS 和 Android)构建聊天应用程序

android - 使用自动截屏测试 android Activity/ View ?

java - 崩溃 onLocationChanged() Android

一旦位置关闭并再次打开,Android 地理围栏不会触发

android - 我们如何在流式传输后缓存 HLS 视频 url

algorithm - 位置点: distance to a specified route

android - GPS 在建筑物内不工作

android - locationListener 在前台服务 30 秒后不起作用