我想检测用户何时更改Android手机的GPS设置。 当用户打开/关闭GPS卫星或通过接入点等进行检测时的含义。
答案 0 :(得分:38)
我发现最好的方法是附加到
<action android:name="android.location.PROVIDERS_CHANGED" />
意图。
例如:
<receiver android:name=".gps.GpsLocationReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
然后在代码中:
public class GpsLocationReceiver extends BroadcastReceiver implements LocationListener
...
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().matches("android.location.PROVIDERS_CHANGED"))
{
// react on GPS provider change action
}
}
答案 1 :(得分:4)
试试这个,
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.i("About GPS", "GPS is Enabled in your devide");
} else {
//showAlert
}
答案 2 :(得分:2)
Impement android.location.LocationListener,你有两个函数
public void onProviderEnabled(String provider);
public void onProviderDisabled(String provider);
使用此功能,您可以了解所请求的提供商何时开启或关闭
答案 3 :(得分:1)
这是一个用于广播接收器的代码示例,用于检测GPS位置的开/关事件:
private BroadcastReceiver locationSwitchStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(intent.getAction())) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGpsEnabled || isNetworkEnabled) {
//location is enabled
} else {
//location is disabled
}
}
}
};
您可以动态注册BroadcastReceiver,而不用更改清单文件:
IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
filter.addAction(Intent.ACTION_PROVIDER_CHANGED);
mActivity.registerReceiver(locationSwitchStateReceiver, filter);
不要忘记在onPause()方法中注销接收器:
mActivity.unregisterReceiver(locationSwitchStateReceiver);