如何获得Android 6.0 Marshmallow的运行时权限的GPS坐标?

时间:2016-10-12 14:32:56

标签: android gps runtime-permissions

我尝试使用manifest.xml中的以下代码设置andriod应用的gps权限

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

但是当我执行时,我无法获得gps坐标。我正在获得“需要许可”的祝酒消息。需要帮忙。这是我的代码段。

LocationManager locationManager = (LocationManager)
                getSystemService(Context.LOCATION_SERVICE);
        LocationListener locationListener = new MyLocationListener();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast toast = Toast.makeText(getApplicationContext(), "no permission", Toast.LENGTH_LONG);
            toast.show();
            return;
        }
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

1 个答案:

答案 0 :(得分:0)

if block

中添加此行
ActivityCompat.requestPermissions(context, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); // 1 is a integer which will return the result in onRequestPermissionsResult

并在您的活动

中附加此代码
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

    switch (requestCode) {
        case 1:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this,"GPS permission granted",Toast.LENGTH_LONG).show();

            //  get Location from your device by some method or code

            } else {
            // show user that permission was denied. inactive the location based feature or force user to close the app
            }
            break;
    }
}