0

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

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

但是当我执行时,我无法获得 gps 坐标。我收到“需要许可”的 Toast 消息。需要帮忙。这是我的代码片段。

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

1 回答 1

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;
    }
}
于 2016-10-12T15:59:25.740 回答