0

There is a lot of similar question and blogs but non of those help me to solve my problem. I have written the code below but the location returning by the getLastKnowLocation is null it's okay sometimes getLastKnowLocation can return null with some conditions. In my code, I requested new updated location if getLastKnowLocation method return null but the onLocationChanged method is not getting called. Here is the code.

@Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.location_provider_layout);
        Intent intent = getIntent();              
        checkPlayServices();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();

        mLocationRequest= LocationRequest.create()
                                         .setInterval(10000)
                                         .setFastestInterval(5000)
                                         .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);


    }



    private boolean checkPlayServices() {
        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
                        .show();
            } else
                finish();

            return false;
        }
        return true;
    }


    @Override
    public void onConnected(@Nullable Bundle bundle) {
        if (mGoogleApiClient.isConnected())
            Log.d(LOCATION_TAG, "Google api is connected");


        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(mLocationRequest);

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {
                final Status status = locationSettingsResult.getStatus();
                switch (status.getStatusCode()) {

                    case LocationSettingsStatusCodes.SUCCESS:;
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            boolean isLocationOn = ActivityCompat.checkSelfPermission(LocationProviderClass.this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED;

                            if (!(isLocationOn)) {
                                String [] runTimePermission=new String[]{Manifest.permission_group.SMS};
                                requestPermissions(runTimePermission, LOCATION_REQUESTCODE);
                            }
                            else
                                computeLocation();
                        } else
                            computeLocation();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        try {
                            status.startResolutionForResult(LocationProviderClass.this, STATUS_INT);
                        } catch (IntentSender.SendIntentException e) {
                            Log.d(LOCATION_TAG, "error in startResolutionForResult");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.d(LOCATION_TAG, "Location setting is canceled");
                        break;
                    default:
                        Log.d(LOCATION_TAG,"Location setting enters into default");

                }
            }
        });


        computeLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.d("PERMISSION_TAG","connection suspended");

    }

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

        if (!mGoogleApiClient.isConnected())
            Log.d(PERMISSION_TAG, "ON connection failed error");
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }

    }


    private void computeLocation() {

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getApplicationContext(), "Fine access location is not granted", Toast.LENGTH_LONG).show();
            }
        }

        location=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(location==null) {
            Toast.makeText(getApplicationContext(), "getLastLocation return null", Toast.LENGTH_LONG).show();
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            Toast.makeText(getApplicationContext(), "getLastLocation return"+location.getLatitude()+" "+location.getLongitude(), Toast.LENGTH_LONG).show();
           //do what ever you want here
        }


    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case  LOCATION_REQUESTCODE: {

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    computeLocation();

                }
                else {

                    Log.d(RUNTIME_PERMISSION_ERROR,"Error in runtime error");
                    Toast.makeText(getApplication(),"The app need location permission", Toast.LENGTH_LONG).show();

                }
                break;
            }



        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == STATUS_INT) {
            switch (resultCode) {
                case Activity.RESULT_OK: {
                    Toast.makeText(getApplicationContext(), "User enabled location permission", Toast.LENGTH_LONG).show();
                    computeLocation();
                    break;
                }
                case Activity.RESULT_CANCELED: {
                    Toast.makeText(getApplication(), "You canceled the permission the app is not going to work", Toast.LENGTH_LONG).show();
                    break;
                }
                default:
                    Toast.makeText(getApplication(), "Permission error", Toast.LENGTH_LONG).show();
            }

        }
    }


    @Override
    public void onLocationChanged(Location location) {
        Log.d(LOCATION_TAG, "onLocationChanged method called");
        Toast.makeText(getApplicationContext(), "onLocationChanged method called"+location.getLongitude()+" "+location.getLatitude(), Toast.LENGTH_LONG).show();

    }


    @Override
    public void onStart() {
        super.onStart();

    }
    @Override
     protected void onResume()
    {
       super.onResume();
        this.mGoogleApiClient.connect();
    }
    @Override
    public void onPause() {
        super.onPause();
        if (this.mGoogleApiClient.isConnected())
         LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
            this.mGoogleApiClient.disconnect();

    }

}
MαπμQμαπkγVπ.0
  • 5,887
  • 1
  • 27
  • 65
Yirga
  • 881
  • 1
  • 12
  • 31

1 Answers1

0

you have to add Listener in order to tell the device you have an action when you got a change location. do something like that

LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
   ...
}
locationManager.requestLocationUpdates(GPS_PROVIDER, intervall, distance, listener);
Basil Battikhi
  • 2,638
  • 1
  • 18
  • 34