【发布时间】:2011-09-16 03:11:06
【问题描述】:
我想检测用户何时打开或关闭 Android 手机的 GPS 设置。 这意味着当用户打开/关闭 GPS 卫星或通过接入点等进行检测时。
【问题讨论】:
-
+1, 5 被标记为最喜欢的问题,只有 1 个被点赞?!
我想检测用户何时打开或关闭 Android 手机的 GPS 设置。 这意味着当用户打开/关闭 GPS 卫星或通过接入点等进行检测时。
【问题讨论】:
我发现最好的方法是附加到
<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
}
}
【讨论】:
<category android:name="android.intent.category.DEFAULT" />?
以下是BroadcastReceiver 检测 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);
【讨论】:
试试这个,
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.i("About GPS", "GPS is Enabled in your devide");
} else {
//showAlert
}
【讨论】:
执行 android.location.LocationListener,你有两个函数
public void onProviderEnabled(String provider);
public void onProviderDisabled(String provider);
使用它您可以了解所请求的提供程序何时打开或关闭
【讨论】: