簡體   English   中英

Android 位置權限錯誤,為空

[英]Android location permission error with null

我是一名學生,目前正在學習並嘗試使用 google map api。 現在,我在獲取位置經緯度方面遇到了問題。 昨天還可以用,今天突然不能用了。 代碼有點長,因為我想表明該應用程序在使用該應用程序之前要求打開該位置的許可,但我認為我沒有正確理解。 我認為該應用程序的啟動方式與我希望的方式不同。

流程應該是,從之前的activity意圖到這個MapsActivity會提示請求權限打開位置,一旦位置開啟,google地圖標記就會更新到當前位置。

現在,應用程序只是不斷崩潰。

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    FusedLocationProviderClient mFusedLocationClient;
    LocationRequest mLocationRequest;
    LocationCallback mLocationCallback;
    double mLocationLat, mLocationLong;

    LocationSettingsRequest.Builder mLocationSettingsBuilder;
    SettingsClient client;
    Task<LocationSettingsResponse> task;
    private static final int REQUEST_CHECK_SETTINGS = 0x1;


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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        //toolbar.setTitle("AskForMech : Maps");
        //toolbar.setLogo(R.drawable.ic_launcher);

        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);

        mLocationCallback = new LocationCallback(){
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if(locationResult==null){
                    return;
                } else {
                    mLocationLat = locationResult.getLastLocation().getLatitude();
                    mLocationLong = locationResult.getLastLocation().getLongitude();
                }
            }
        };

        setLocationRequestSettings();

    }

    public void getLocation(){ //error is here
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        mLocationLat = location.getLatitude();
        mLocationLong = location.getLongitude();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        getLocation(); //error is here
        LatLng pos = new LatLng(mLocationLat, mLocationLong);
        mMap.addMarker(new MarkerOptions().position(pos).title("You!"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 18.00f));
    }

    @Override
    protected void onResume() {
        super.onResume();
        //startLocationUpdate();
         requestLocationUpdate();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if(mFusedLocationClient != null){

            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
            Toast.makeText(MapsActivity.this, "Listener is removed.", Toast.LENGTH_SHORT).show();
        }
    }

    private void requestLocationUpdate(){
        mLocationSettingsBuilder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
        client = LocationServices.getSettingsClient(MapsActivity.this);

        task = client.checkLocationSettings(mLocationSettingsBuilder.build());

        task.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
            @Override
            public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

                startLocationUpdate();
            }
        });

        task.addOnFailureListener(MapsActivity.this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {

                if(e instanceof ResolvableApiException){
                    try{

                        ResolvableApiException resolvable = (ResolvableApiException) e;
                        resolvable.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);

                    }catch(IntentSender.SendIntentException sendEx) {

                    }
                }
            }
        });
    }

    private void setLocationRequestSettings(){

        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(3000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    private void startLocationUpdate(){
            // Here, thisActivity is the current activity
            if (ContextCompat.checkSelfPermission(MapsActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {

                    showExplanation();

                } else {
                    ActivityCompat.requestPermissions(MapsActivity.this,
                            new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                            0);

                }
            } else {

                mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
                Toast.makeText(MapsActivity.this, "Location permission was granted!", Toast.LENGTH_SHORT).show();
            }
        }

    private void showExplanation(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);

        builder.setTitle("Requires Location Permission.");
        builder.setMessage("This app needs location permission to get the location information.");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ActivityCompat.requestPermissions(MapsActivity.this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        0);
            }
        });

        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MapsActivity.this, "Sorry, this function cannot be used until permission is granted.",Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();
    }
}

您應該使用回調方法onLocationChanged()而不是getLastKnownLocation () 實際上, getLastKnownLocation()可以返回null (請參閱此處

我更喜歡使用檢測到位置更改后調用的onLocationChanged() 事實證明它對我很有用。

如果您在實現 LocationListener 時遇到任何麻煩,請查看此帖子: https : //stackoverflow.com/a/42218626/3780625

最好的事物

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM