How to get last known location for Location manager in Android?

后端 未结 7 1449
-上瘾入骨i
-上瘾入骨i 2021-01-11 10:34

I am using simple location manager object to get lastKnownLocation() of device but getting null object in

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-11 10:56

    To fetch the last location, you can refer to the above provided answers where you can use Location Manager or FusedLocationClient

    But You can also make use of LocationServices which is faster than other approaches.

    So let me provide a brief working :

    1) Add these two dependencies in your gradle app file

    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    

    2) Add these permissions in the manifest file outside applicationtag

    
    
    

    3) Declare variable outside onCreate

    private FusedLocationProviderClient fusedLocationClient;
    

    4) Now inside onCreate :

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    fetchLastLocation();
    

    5) No define fetchLastLocation method

    private void fetchLastLocation() {
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    Activity#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for Activity#requestPermissions for more details.
    //                    Toast.makeText(MainActivity.this, "Permission not granted, Kindly allow permission", Toast.LENGTH_LONG).show();
                    showPermissionAlert();
                    return;
                }
            }
            fusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                                Log.e("LAST LOCATION: ", location.toString());
                            }
                        }
                    });
    
        }
    

    6) Now define other two method for permission request

    @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case 123: {
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                        // permission was denied, show alert to explain permission
                        showPermissionAlert();
                    }else{
                        //permission is granted now start a background service
                        if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                                && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                            fetchLastLocation();
                        }
                    }
                }
            }
        }
    
        private void showPermissionAlert(){
            if (ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(MainHomeActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainHomeActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
            }
        }
    

    Note : Replace context with your class context

    You will get your location in Logcat.

    Hope this will hope you or somebody else

提交回复
热议问题