简体   繁体   中英

Android: pausing an app in background and resuming in foreground

I have an Android app that currently obtains the user's current location and uses it to update the current position on a map; it does this in the background and the foreground so that this functionality runs during the lifecycle of the app regardless of whether the user is current using the app or something else. Now, I'm trying to modify the code so that the update position code only runs while the app is in the foreground; the update location feature is deactivated when in the background but is reinvoked when brought to the fore.

I've read the Lifecycle section on the Android manual pages and have concocted the following code (Below are sections relevant to location and location listening.)

However, the declarations @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) and @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) give unresolved symbol errors for OnLifecycleEvent. When I include "import androidx.lifecycle.OnLifecycleEvent;", I get dialogues in the Studio IDE saying, "method appInResumeState() is never used" and "method appInPauseState() is never used". I am not explicitly calling this, but I thought that the annotation for OnLifecycleEvent would handle calls to these methods?

Also, another question if I may; in this page , the flow chart says that "OnResume" is also called when the app is initialised for the first time. Is there any way to call this only when the app is brought back from background?

Sorry if the code is a bit messy; I plan to get something working and when I'm comfortable with it, then I'll refactor it.

In build.gradle

dependencies 
{
  def lifecycle_version = "2.2.0"
  def arch_version = "2.1.0"

  // Lifecycles only (without ViewModel or LiveData)
  implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

  // Annotation processor
  annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
  implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

}




import android.location.LocationListener;
import android.location.LocationManager;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.ProcessLifecycleOwner;


public class GoRamble extends FragmentActivity implements View.OnClickListener, GoogleMap.OnMapClickListener, OnMapReadyCallback, GoogleMap.OnMarkerClickListener, LifecycleObserver
{

private LocationManager mLocationManager;

public static final int LOCATION_UPDATE_MIN_DISTANCE = 10; // 10 metres - to be changed
public static final int LOCATION_UPDATE_MIN_TIME = 5000; //  5000 - 5 seconds - to be changed


protected void onCreate(Bundle savedInstanceState)
{
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}

public void onMapReady(GoogleMap googleMap)
{
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        bFineOK = true;

    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        bCoarseOK = true;

    if(bFineOK) isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

    if(bCoarseOK) isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);


    if( bCoarseOK && bFineOK ) 
    {

        if (isNetworkEnabled) 
        {
                mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                        LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListenerNetwork);
        }

        if (isGPSEnabled) 
        {
                mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListenerGPS);

        }
    }

}



private LocationListener mLocationListenerNetwork = new LocationListener() {   
    @Override
    public void onLocationChanged(Location location) {

        mLocation = location;  // mLocation is a member variable which will also be used elsewhere
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mLocation.getLatitude(), mLocation.getLongitude()))); // move view to new location
    }
}


private LocationListener mLocationListenerGPS = new LocationListener() {   
        @Override
        public void onLocationChanged(Location location)
        {

            mLocation = location;
            mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(mLocation.getLatitude(), mLocation.getLongitude())));
        }
}


@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void appInResumeState() 
{
  if(bFineOK) mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListenerGPS);
  if(bCoarseOK) mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DISTANCE, mLocationListenerNetwork);

}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void appInPauseState() 
{
  if(bFineOK) mLocationManager.removeUpdates(mLocationListenerGPS);
  if(bCoarseOK) mLocationManager.removeUpdates(mLocationListenerNetwork);
}

}

When I include "import androidx.lifecycle.OnLifecycleEvent;", I get dialogues in the Studio IDE saying, "method appInResumeState() is never used" and "method appInPauseState() is never used"

don't worry about that because it will be handle in runtime by annotation

the flow chart says that "OnResume" is also called when the app is initialised for the first time

Sure it's lifecycle callback always call when Activity visible to user (first time and when return from background). You can use global boolean to handle if you want.

But in your code I think you should addObserver by Activity Lifecycle Owner, In case you want to listen ProcessLifecycleOwner you should put your code inside Application . In your GoRamble you should use ActivityLifecycle by this

getLifecycle().addObserver(this)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM