前言
因为上一篇博客的缘故,发现安卓9.0的定位跟GPS是否开启有很大关系,因此就想到安卓能不能监听GPS的状态,类似于广播这种注册接收等,经过搜索发现,安卓系统还是有预留这个监听,也许大家对这个需求可能不是太需要,但是我的需求场景是需要的。
GPS 状态的监听
Android 中有关于GPS状态的常量,存在于Setting中
Settings.Secure.getUriFor(Settings.System.LOCATION_PROVIDERS_ALLOWED) 该常量 LOCATION_PROVIDERS_ALLOWED 的解释如下 * Comma-separated list of location providers that activities may access. Do not rely on * this value being present in settings.db or on ContentObserver notifications on the * corresponding Uri.
谷歌翻译:
*活动可以访问的以逗号分隔的位置提供者列表。 不要依赖
*此值存在于settings.db或ContentObserver通知中
*相应的Uri。
然后通过注册ContentObserver来观察GPS的状态改变,因此需要对象继承自ContentObserver
ContentObserver部分代码
/**
* Receives call backs for changes to content.
* Must be implemented by objects which are added to a {@link ContentObservable}.
*/
public abstract class ContentObserver {
private final Object mLock = new Object();
private Transport mTransport; // guarded by mLock
Handler mHandler;
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public ContentObserver(Handler handler) {
mHandler = handler;
}
定义GPS观察者监听对象,当用户点击手机上的GPS(Gps快捷开关也可以)可以触发该观察者回调.
private final ContentObserver mGpsMonitor = new ContentObserver(null) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (mLocationManager != null) {
boolean enabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
notifyChanged(enabled);
}
}
};
在onCreate/onStart中去注册该监听,我维护了一个单例,可以再多个界面注册监听/移除监听等.
GpsMonitor.getInstance().addListener(getLocalClassName(), onGpsMonitorChangedListener).registerGpsMonitor(this);
在onDestroy/onStop中销毁监听.
GpsMonitor.getInstance().removeListener(getLocalClassName());
上述操作完成后,即可动态的监听到GPS状态的变化(当用户点击高精度,移动网络provider或者仅限设备)均会触发该监听,亲测可用。
文末彩蛋
大家看到上述方法有点类似于安卓中广播的注册使用,确实,这个模式貌似已经被@Deprecated了,谷歌已经不建议这样使用了。
/**
* @deprecated Use {@link android.provider.Settings.Secure#LOCATION_PROVIDERS_ALLOWED}
* instead
*/
@Deprecated
public static final String LOCATION_PROVIDERS_ALLOWED = Secure.LOCATION_PROVIDERS_ALLOWED;
谷歌真的建议使用广播注册的方式来监听GPS的状态改变.
因此有多了上面建议的两个常量
* {@link LocationManager#MODE_CHANGED_ACTION} (or * {@link LocationManager#PROVIDERS_CHANGED_ACTION})
因此,再使用这个方式的时候,使用广播注册,IntentFilter添加上面两个action,当GPS状态改变时,广播会接收到这个通知.
上述两种方法均测试通过。