Search code examples
androidbuttonorientationbackground-serviceandroid-savedstate

Save Instance State of GPS and enabled buttons


My problem is that when i rotate the GPS, then I can't stop the LocationServices.FusedLocationApi. This only happens after I have rotated the screen. If I dont change the orientation the start and stop works fine.

This should controll if it should update or not

private boolean mRequestingLocationUpdates;

Here is the values I want to save

public void onSaveInstanceState(Bundle savedInstanceState) {
        savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
        savedInstanceState.putBoolean(REQUESTING_SAVED_FIRSTTIME, isFirstTime);
        savedInstanceState.putString(LAST_UPDATED_TIME_STRING_KEY, mLastUpdateTime);
        super.onSaveInstanceState(savedInstanceState);
    }

    private void updateValuesFromBundle(Bundle savedInstanceState) {
        Log.i(TAG, "Updating values from bundle");
        if (savedInstanceState != null) {
            if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
                mRequestingLocationUpdates = savedInstanceState.getBoolean(REQUESTING_LOCATION_UPDATES_KEY);

                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }

                if (lightsOn != null) {
                    lightsOn.setVisibility(View.VISIBLE);
                }
            }


            if (savedInstanceState.keySet().contains(IS_FIRST_TIME_KEY)) {
                isFirstTime = savedInstanceState.getBoolean(IS_FIRST_TIME_KEY);
            }

            // Update the value of mLastUpdateTime from the Bundle and update the UI.
            if (savedInstanceState.keySet().contains(LAST_UPDATED_TIME_STRING_KEY)) {
                mLastUpdateTime = savedInstanceState.getString(LAST_UPDATED_TIME_STRING_KEY);
            }
        }
    }

START and STOP Location updates

protected void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}


protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

onCreate With buttons to controll the start and stop

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainreal);

    // Starting the gps and location updates
    mStartTrackerButton = (Button) findViewById(R.id.buttonStart);
    mStartTrackerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(MainReal.this, "START", Toast.LENGTH_SHORT).show();

            // Set true, will generate a new date, and a new startpoint in database
            isFirstTime = true;

            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.VISIBLE);
            }

            if (lightsOn != null) {
                lightsOn.setVisibility(View.VISIBLE);
            }

            mRequestingLocationUpdates = true;
            startLocationUpdates();
        }
    });


    // STOP the gps and location updates
    mStopTrackerButton = (Button) findViewById(R.id.buttonStop);
    mStopTrackerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mProgressBar != null) {
                mProgressBar.setVisibility(View.GONE);
            }

            if (lightsOn != null) {
                lightsOn.setVisibility(View.GONE);
            }

            mRequestingLocationUpdates = false;
            stopLocationUpdates();
        }
    });


    // Setting up google api client
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();


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


    mRequestingLocationUpdates = false;

    // Update values using data stored in the Bundle.
    updateValuesFromBundle(savedInstanceState);
}

Solution

  • Needed to add this inside onPause(). Could have some explanation about it.

      @Override
        protected void onPause() {
            super.onPause(); 
            if (mGoogleApiClient.isConnected()) {
                stopLocationUpdates();
            }  
         }