检查在启动新活动时是否调用onStop活动

时间:2017-02-25 12:16:57

标签: android performance android-activity android-lifecycle

我正在努力解决问题。在我的应用程序中,我需要确定是否因为启动新活动而调用onStop方法,或者在用户单击主页按钮或已切换到另一个应用程序后调用它。

我有BaseActivity类,我需要在这里查看。

我试图找到一种方法来做到这一点,但不幸的是仍然没有找到解决方案。

也许有一种解决方法。

我们的想法是区分onStop方法调用的发起者。

如果有任何帮助,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案是注册ActivityLifecycleCallbacks并保存调用onResume的最后一个活动的引用名称:

public class ActivityChecker implements Application.ActivityLifecycleCallbacks {
  private static ActivityChecker mChecker;
  private String mCurrentResumedActivity = "";

  public static ActivityChecker getInstance() {
    return mChecker = mChecker == null ? new ActivityChecker() : mChecker;
  }

  // If you press the home button or navigate to another app, the onStop callback will be called without touching the mCurrentResumedActivity property.
  // When a new activity is open, its onResume method will be called before the onStop from the current activity.
  @Override 
  public void onActivityResumed(Activity activity) {
    // I prefer to save the toString() instead of the activity to avoid complications with memory leaks. 
    mCurrentResumedActivity = activity.toString();
  }   


  public boolean isTheLastResumedActivity(@NonNull Activity activity) {
    return activity.toString().equals(mCurrentResumedActivity);
  }

  // [...] All other lifecycle callbacks were left empty
}

ActivityLifecycleCallbacks可以在Application类中注册:

public class App extends Application {

  public App() {
    registerActivityLifecycleCallbacks(ActivityChecker.getInstance());
  }

}

不要忘记在你的清单中注册它:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name">    

    <application
        ...
        android:name=".App"
        > ...
    </application>
</manifest>

然后,您可以在基础活动中使用它。

public class MyBaseActivity {
  @Override protected void onStop() {
    if(ActivityChecker.getInstance().isTheLastResumedActivity(this)) {
      // Home button touched or other application is being open.
    }
  }
}

<强>参考文献:

注册自定义Application类和ActivityLifecycleCallbacks:https://developer.android.com/reference/android/app/Application.html

写完这篇文章之后,我发现这个链接带有一些其他选项来检索当前恢复的活动:How to get current foreground activity context in android?

答案 1 :(得分:-1)

您可以使用SharedPreferences进行检查:

@Override
    protected void onStop() {
        super.onStop();
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        pref.edit().putBoolean("IfOnStopCalled", true).apply();
    }

签入您的BaseActivity:

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
Boolean IfOnStopCalled = pref.getBoolean("IfOnStopCalled",false);

if(IfOnStopCalled){
  //Do your action
}
else{
 //Do your action
}