请求位置权限

时间:2016-10-10 00:23:25

标签: android permissions

我的应用正在使用API​​ 23,而我正在使用我的三星Galaxy S5进行测试。我也在使用GoogleMaps API。

在onConnected()方法中,我想检索用户的当前位置,所以我有这个:

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

但只有这一点,它带有下划线红色,并出现以下错误:

调用需要用户可能拒绝的权限:代码应明确检查权限是否可用(使用CheckPermission)...

它给了我“添加权限检查”的选项,它插入一些代码并向其添加内容,因此onConnected()方法就像这样

@Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG, "oOnConnected() called");

        boolean r = ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED;
        Log.i(TAG, "result = : " + r );

        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED ) {
            Log.i(TAG, "PERMISSIONS NOT SET");
            requestPermissions(new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, 100);
            return;

        }

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);     
        String s = String.valueOf(mLastLocation.getLatitude()) + " " +
                String.valueOf(mLastLocation.getLongitude());
        Log.i(TAG, "CURRENT LOCATION: " + s);
    }

运行代码时出现问题: (1)当我的设备上的位置启用它工作正常,我看到我在终端的当前位置。我检查了r的值,它是假的......

(2)当禁用位置时,当我运行应用程序时,它会崩溃并显示“停止工作”消息。我检查终端并因为mLastLocation对象为null或其他东西而崩溃。但是这些行不应该被执行,它应该要求权限。我检查了r的值,它也是假的。

为什么两种情况都是假的?如何修复此问题以获取在禁用位置时弹出的权限?

1 个答案:

答案 0 :(得分:0)

我的解决方案是

清单文件中的

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

<meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_KEY" />

我创建了一个用于保存地图的片段

public class BlankFragment extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleApiClient googleApiClient = null;
    FusedLocationProviderApi fusedLocationProviderApi;
    LocationRequest locationRequest;

    final int PERMISSIONS_REQUEST = 900;

    private static final LatLng STUTTGART = new LatLng(48.792925, 9.204344);
    private static final float STUTTGART_ZOOM = 16;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLocation();
    }

    private void getLocation() {
        locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        fusedLocationProviderApi = LocationServices.FusedLocationApi;

        googleApiClient = new GoogleApiClient.Builder(getContext())
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        googleApiClient.connect();
    }


    @Override
    public void onConnected(Bundle arg0) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                        PERMISSIONS_REQUEST);
            return;
        }
        fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);
    }

    @Override
    public void onLocationChanged(Location location) {
        Toast.makeText(getContext(), "location :"+location.getLatitude()+" , "+location.getLongitude(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (googleApiClient.isConnected()) {
            googleApiClient.disconnect();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMap.clear();

        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(STUTTGART, STUTTGART_ZOOM));
        googleMap.getUiSettings().setMapToolbarEnabled(false);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay!
                    fusedLocationProviderApi.requestLocationUpdates(googleApiClient, locationRequest, this);

                }
            }
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

xml文件看起来像这样

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bemaxnet.test.maps.fragment.BlankFragment">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <Button
        android:id="@+id/currentLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="current location"
        android:drawableLeft="@android:drawable/ic_menu_add"/>

</FrameLayout>

最后在app gradle中添加了这些依赖项

compile 'com.google.android.gms:play-services-maps:9.6.1'
compile 'com.google.android.gms:play-services-location:9.6.1'