简体   繁体   English

Android:在后台暂停应用程序并在前台恢复

[英]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;我有一个 Android 应用程序,它当前获取用户的当前位置并使用它来更新 map 上的当前 position; 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;现在,我正在尝试修改代码,以便更新 position 代码仅在应用程序处于前台时运行; 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.)我已阅读 Android 手册页上的生命周期部分,并编写了以下代码(以下是与位置和位置监听相关的部分。)

However, the declarations @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) and @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) give unresolved symbol errors for OnLifecycleEvent.但是,声明 @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) 和 @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) 为 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".当我包含“import androidx.lifecycle.OnLifecycleEvent;”时,我在 Studio IDE 中得到对话,说“从未使用方法 appInResumeState()”和“从未使用方法 appInPauseState()”。 I am not explicitly calling this, but I thought that the annotation for OnLifecycleEvent would handle calls to these methods?我没有明确地调用它,但我认为 OnLifecycleEvent 的注释会处理对这些方法的调用?

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.此页面中,流程图显示应用程序第一次初始化时也会调用“OnResume”。 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在 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"当我包含“import androidx.lifecycle.OnLifecycleEvent;”时,我在 Studio IDE 中得到对话,说“从未使用过 appInResumeState() 方法”和“从未使用过 appInPauseState() 方法”

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流程图显示第一次初始化应用程序时也会调用“OnResume”

Sure it's lifecycle callback always call when Activity visible to user (first time and when return from background).当然,当 Activity 对用户可见时(第一次和从后台返回时),它的生命周期回调总是调用。 You can use global boolean to handle if you want.您可以根据需要使用全局 boolean 来处理。

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 .但是在你的代码中,我认为你应该通过 Activity Lifecycle Owner 添加Observer,如果你想听ProcessLifecycleOwner你应该把你的代码放在Application中。 In your GoRamble you should use ActivityLifecycle by this在您的GoRamble ,您应该使用 ActivityLifecycle

getLifecycle().addObserver(this)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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