在Marshmallow中运行时请求权限组位置的正确方法是什么?

时间:2016-09-03 00:22:21

标签: android android-6.0-marshmallow android-permissions

我正在尝试创建一个测试应用程序,以便我可以使用LocationManager,但我甚至无法在运行时传递新的愚蠢权限请求。我做错了什么,为什么他们这么混乱/复杂?

public class MainActivity extends AppCompatActivity {

    private static final int LOCATION_GROUP_PERMISSION_REQUEST = 1;
    private boolean locationPermissionGranted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getLocationPermission();

        if(locationPermissionGranted) {
            LocationManager locationManager =
                    (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            String provider = LocationManager.GPS_PROVIDER;
            try {
                Location location = locationManager.getLastKnownLocation(provider);
                updateTextView(location);
            } catch(SecurityException e) {
                Log.e("PERMISSION_DENIED", e.getMessage());
            }
        }

        //registerReceiver(gpsReciever, new IntentFilter("android.location.PROVIDERS_CHANGED"));
    }

    private void updateTextView(Location location) {
        Double latitude = location.getLatitude();
        Double longitude = location.getLongitude();
        TextView view = (TextView) findViewById(R.id.textView);
        view.setText(getString(R.string.lat_long_string, latitude, longitude));
    }

    private void getLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission_group.LOCATION},
                        LOCATION_GROUP_PERMISSION_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) {
        // Make sure it's our original READ_CONTACTS request
        if (requestCode == LOCATION_GROUP_PERMISSION_REQUEST) {
            if (grantResults.length == 1 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                locationPermissionGranted = true;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:6)

  

在Marshmallow中运行时请求权限组位置的正确方法是什么?

你没有。您在运行时请求权限,而不是权限组。从代码中删除引用权限组的所有内容(例如Manifest.permission_group.LOCATION)。将其替换为引用权限的代码(例如Manifest.permission.ACCESS_FINE_LOCATION)。

相关问题