一個可能的解決方案是註冊一個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
}
ActivityLifecycleCallback S能在您的應用程序類進行註冊:
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.
}
}
}
參考文獻:
註冊您的自定義應用程序類和ActivityLifecycleCallbacks:https://developer.android.com/reference/android/app/Application.html
寫這之後,我發現了一些其他的選擇這個鏈接,檢索當前恢復活動:How to get current foreground activity context in android?。
你可以添加一個'protected boolean otherActivityCalled = false;'當你啓動這個'otherActivity'並且在你的'onStop'鉤子中檢查它時,將這個設置爲'true'。如果它是'false',那意味着你的'currentActivity'由於另一個原因而被停止了。 – AnixPasBesoin