2017-02-25 36 views
0

我正在嘗試解決問題。在我的應用程序中,我需要確定onStop方法是否因爲啓動了新的活動而被調用,或者在用戶點擊home按鈕或切換到其他應用程序後調用了方法。檢查是否在開始新活動時調用onStop

我有BaseActivity類,我需要在這裏檢查它。

我試圖找到一種方法來做到這一點,但不幸的是仍然沒有找到解決方案。

也許有一個解決方法。

這個想法是區分onStop方法調用的發起者。

我將不勝感激任何幫助。在BaseActivity

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

檢查:

+0

你可以添加一個'protected boolean otherActivityCalled = false;'當你啓動這個'otherActivity'並且在你的'onStop'鉤子中檢查它時,將這個設置爲'true'。如果它是'false',那意味着你的'currentActivity'由於另一個原因而被停止了。 – AnixPasBesoin

回答

-1

您可以使用SharedPreferences檢查它

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

if(IfOnStopCalled){ 
    //Do your action 
} 
else{ 
//Do your action 
} 
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 
} 

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?

相關問題