在Android操作系统中,在“设置”中 - > “位置服务”,有一个名为“访问我的位置”的切换按钮,可用于禁用&启用应用程序的位置信息访问。
目前,我正在开发一个位置服务应用程序。我想知道,我怎么能在我的Android项目中听这个设置?当用户禁用或启用“访问我的位置”时,是否有任何广播接收器可以立即知道?
如果没有任何广播接收器,我如何在Android项目中收听此更改?
答案 0 :(得分:6)
这对我有用:
将接收器添加到清单文件:
<receiver
android:name="com.eegeo.location.LocationProviderChangedReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
检查接收方中的两个位置提供者:
public class LocationProviderChangedReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
boolean anyLocationProv = false;
LocationManager locationManager = (LocationManager) MyMainActivity.context.getSystemService(Context.LOCATION_SERVICE);
anyLocationProv |= locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
anyLocationProv |= locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i("", "Location service status" + anyLocationProv);
}
}
虽然这个接收器由于显而易见的原因被多次调用,但这会告诉你状态。
答案 1 :(得分:1)
你可以通过这种方式更简单地做到这一点。在您的BroadcastReceiver的 onReceive()方法中:
ContentResolver contentResolver = getContext().getContentResolver();
// Find out what the settings say about which providers are enabled
int mode = Settings.Secure.getInt(
contentResolver, Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF);
if (mode == Settings.Secure.LOCATION_MODE_OFF) {
// Location is turned OFF!
} else {
// Location is turned ON!
}
〜感谢此代码:LocationManagerTest.java
答案 2 :(得分:0)
您可以使用以下代码检查是否启用位置服务
LocationManager lm = null;
boolean gps_enabled,network_enabled;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){}
try{
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){}
if(!gps_enabled && !network_enabled){
dialog = new AlertDialog.Builder(context);
dialog.setMessage(context.getResources().getString(R.string.gps_network_not_enabled));
dialog.setPositiveButton(context.getResources().getString(R.string.open_location_settings), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
context.startActivity(myIntent);
//get gps
}
});
dialog.setNegativeButton(context.getString(R.string.Cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
}
});
dialog.show();
}