Android 5.1.1上的位置权限

时间:2017-06-03 17:37:18

标签: android permissions request

在我的应用中,我需要用户位置。

我意识到我必须要求许可,但我如何在Android 5.1.1上执行此操作,用户无法更改权限。我编写的代码无处不在但没有结果。

我该怎样进行?

"com.quantcast" % "quantserve_shared" % "3.5.3166" % "compile->master"
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.Manifest;

//import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
//import com.google.android.gms.maps.model.LatLng;
//import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.common.api.*;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
, GoogleApiClient.ConnectionCallbacks
        //, OnConnectionFailedListener

{

    private GoogleMap mMap;
   // public GoogleApiClient.Builder mGoogleApiClient = new GoogleApiClient.Builder(this);
   private GoogleApiClient mGoogleApiClient;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public double latitude;
    public double longitude;

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


        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        //mMainActivity.onConnected(bBundle);

        Log.d("OnCreate", "enter 1");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                //.enableAutoManage(this /* FragmentActivity */,
                //       this /* OnConnectionFailedListener */)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                // .addApi(Places.GEO_DATA_API)
                //.addApi(Places.PLACE_DETECTION_API)
                .build()
        ;
        mGoogleApiClient.connect();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d("OnCreate", "enter in if1 ");

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                Log.d("OnCreate", "enter in if2 ");
                

            } else {
                Log.d("OnCreate", "enter in else2 Request permission ");
                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            //Request location updates: Popytka
            //locationManager.requestLocationUpdates(provider, 400, 1, this);
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
            if (mLastLocation != null) {
                Log.d("OnCreate", "enter2");
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();
                Log.d("OnCreate longitude", String.valueOf(longitude));
            }
        }
    }
    //public MainActivity mMainActivity = new MainActivity();
    Bundle bBundle;

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

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        //Request location updates:
                        //locationManager.requestLocationUpdates(provider, 400, 1, this);
                        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));



                        if (mLastLocation != null) {
                            Log.d("OnCreate","enter20");
                            latitude = mLastLocation.getLatitude();
                            longitude = mLastLocation.getLongitude();
                            Log.d("OnCreate longitude-0", String.valueOf(longitude));
                        }
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {

        //System.out.println("onMapReady in");
        mMap = googleMap;
        //latitude = -34;
        //longitude = 151;
        float zoom = 5;
        double laRe = latitude, loRe = longitude+1;
        // Add a marker in Sydney and move the camera
        LatLng user = new LatLng(latitude, longitude), rest = new LatLng(laRe, loRe);
        //LatLng rest = new LatLng(laRe, loRe);

        mMap.addMarker(new MarkerOptions().position(user).title("Marker in USER"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, zoom));


        mMap.addCircle(new CircleOptions()
                .center(user)
                .radius(200000)
                .strokeColor(0)
                .fillColor(0x4000ff00));

        GroundOverlayOptions restPos = new GroundOverlayOptions()
                .image(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
                .position(new LatLng(laRe, loRe), 200000f);
        mMap.addGroundOverlay(restPos);
    }

        @Override
        public void onConnected (Bundle bBundle){

        }

    protected void onStart() {
        //mGoogleApiClient.connect();
        super.onStart();
        //mGoogleApiClient.ConnectionCallbacks; //(this);
    }

    protected void onStop() {
        // mGoogleApiClient.disconnect();
        super.onStop();
    }

    public void onConnectionSuspended(int i) {

    }

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

    }

}

SDK 25

1 个答案:

答案 0 :(得分:0)

Android 6.0+需要运行时权限,但如果您需要这是请求运行时权限的最简单代码。

 String [] permissions=new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            List<String> listPermissionsNeeded = new ArrayList<>();
            for (String permission:permissions) {
                if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
                    listPermissionsNeeded.add(permission);
                }
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
            }
  

更新

试试这个 - &gt;

首先,创建一个LocationRequest对象:

 // Create the LocationRequest object 
 mLocationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

然后,确保用户已授予使用位置的权限。如果是,请从requestLocationUpdates获取位置,如下所示:

void getLocation() { 
    Location location = null; 
    if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

        /*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/ 

    } else { 
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    } 

    mLastLocation = location; 
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
} 

如果您只需要一个没有持续监控的位置,请务必删除更新。这样,您将永远不会获得null位置。