我想检测用户何时更改Android手机的GPS设置.当用户打开/关闭GPS卫星或通过接入点等进行检测时的含义
Dre*_*ejc 39
正如我已经发现的那样,最好的方法是附加到
<action android:name="android.location.PROVIDERS_CHANGED" />
Run Code Online (Sandbox Code Playgroud)
意图.
例如:
<receiver android:name=".gps.GpsLocationReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
然后在代码中:
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
}
}
Run Code Online (Sandbox Code Playgroud)
mat*_*dev 15
以下是BroadcastReceiver检测 GPS 位置 ON/OFF 事件的代码示例:
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
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
您可以BroadcastReceiver动态注册您的清单文件,而不是更改您的清单文件:
IntentFilter filter = new IntentFilter(LocationManager.PROVIDERS_CHANGED_ACTION);
filter.addAction(Intent.ACTION_PROVIDER_CHANGED);
mActivity.registerReceiver(locationSwitchStateReceiver, filter);
Run Code Online (Sandbox Code Playgroud)
不要忘记在您的onPause()方法中取消注册接收器:
mActivity.unregisterReceiver(locationSwitchStateReceiver);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21023 次 |
| 最近记录: |