在设置中收听位置访问禁用/启用

Mel*_*lon 8 android broadcastreceiver android-intent android-broadcast

在Android操作系统中,在" 设置 " - >" 位置服务 "中,有一个名为" 访问我的位置 " 的切换按钮,可用于禁用和启用应用程序的位置信息访问.

目前,我正在开发一个位置服务应用程序.我想知道,我怎么能在我的Android项目中听这个设置?当用户禁用或启用" 访问我的位置 " 时,是否有任何广播接收器可以立即知道?

如果没有任何广播接收器,我如何在Android项目中听取此更改?

M. *_*han 6

这对我有用:

将接收器添加到清单文件:

<receiver
        android:name="com.eegeo.location.LocationProviderChangedReceiver">
        <intent-filter>
            <action android:name="android.location.PROVIDERS_CHANGED" />
        </intent-filter>
    </receiver>
Run Code Online (Sandbox Code Playgroud)

检查接收器中的两个位置提供者

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);


    }

}
Run Code Online (Sandbox Code Playgroud)

虽然这个接收器由于显而易见的原因不止一次被调用,但这会告诉你状态.

  • 如果您的应用程序面向 Android 8.0(API 级别 26)或更高版本,则此操作将不起作用:[在清单中注册隐式广播的广播接收器已被禁用](https://developer.android.com/about/versions/oreo/背景#广播) (2认同)

Kar*_*thi 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();

    }
Run Code Online (Sandbox Code Playgroud)

  • 您好,我的问题不是关于如何检查该值,而是关于如何监听更改,这意味着如何在代码中获取用户已在设置中更改此位置访问权限的通知,然后获取更改后的值。 (3认同)