2016-07-14 73 views
5

我的應用程序旨在僅允許登錄的用戶訪問活動。如果用戶註銷,則將共享首選項布爾值isLogged in設置爲false,並且用戶不應訪問除LoginActivity之外的其餘活動。如何關閉所有活動並退出應用程序

但是,我可以通過按後退按鈕訪問所有以前打開的活動。

我會用finish();同時打開的每個活動,但後來我想用戶仍然使用後退按鈕,而他們已經登錄。

我試圖從其他類似的問題解決方案,如

Intent intent = new Intent(getApplicationContext(), LoginActivity.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.putExtra("EXIT", true); 
startActivity(intent); 

和我LoginActivity的onCreate()我加入

if (getIntent().getBooleanExtra("EXIT", false)) { 
     finish(); 
    } 

當我按下注銷選項,在p而不是先前的活動。

有什麼建議請幫幫我嗎?

+0

試試這個.. http://stackoverflow.com/a/38268217/6334037 – user392117

回答

4

你應該使用這個標誌,即清除任務,並創建一個新的

Intent intent = new Intent(getApplicationContext(), LoginActivity.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
startActivity(intent); 
+1

這對我有效。 – Mwas

+1

不客氣! –

2

嘗試添加在陣列中的所有活動,當你要刪除剛剛從陣列中取出,並完成該活動。看到這裏Remove activity from stack

3
if (getIntent().getBooleanExtra("EXIT", false)) { 
     finish(); 
android.os.Process.killProcess(android.os.Process.myPid()); 
    } 
3

我的回答試試這個

您需要在意圖上添加這些標誌..

Intent intent = new Intent(getApplicationContext(), LoginActivity.class); 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK); 
intent.putExtra("EXIT", true); 
startActivity(intent); 
finish(); 
0

我面對類似的情況。正如我想到的那樣,即使我在開始時調用了finish()函數,整個onCreate()函數也會被執行。然後它會結束。在我的場景中,在onCreate()函數中,我調用另一個Activity。所以即使主要活動在onCreate()之後完成,第二項活動仍然存在。所以我的解決辦法是,

private boolean finish = false;

中的onCreate

()的主要功能,

if(intent.getBooleanExtra("EXIT", false)) { 
     finish(); 
     finish = true; 
    } 

,我把支票在所有導航

if(!finish) { 
     Intent intent = new Intent(MainActivity.this, LoginActivity.class); 
     startActivity(intent); 
     finish(); 
    } 

我的退出功能是,

Intent intent = new Intent(getApplicationContext(), MainActivity.class); 
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.putExtra("EXIT", true); 
    startActivity(intent); 
相關問題