2013-11-26 53 views
14

我的應用程序具有以下流動如何完成所有活動並在android中關閉應用程序?

首頁 - >屏幕1->屏幕2->屏幕3->屏幕4->屏幕5>首頁 - >屏幕2->首頁 - >屏幕3

我的問題是,當我試圖關閉應用程序時,Home活動會在我嘗試關閉應用程序時每次打開。

我只想在用戶在主屏幕上按下設備的後退鍵時關閉應用程序。

+0

看到這個:http://stackoverflow.com/questions/4758462/android-finish-all-activities – Avijit

回答

52

存在將完成當前的活動和所有父活動finishAffinity()方法,但它只能在搭載Android 4.1或更高版本

+2

這是一個救命......! – GAMA

0

android:noHistory="true"添加到您的活動清單文件中。

+0

我敢打賭,當他按下時他想回到前一個屏幕,但只有當他在主屏幕上時才關閉它們。 –

0

有2種方式爲您解決問題

1)調用完成()後startActivity(意向),在每一個活動

2)設置機器人:在menifest文件中的每個標籤launchMode =「singleInstance」

我想第二個辦法是最好的解決問題,但你也可以使用第一種方式

2

這很適合我在所有版本啓動畫面3。 關閉所有以前的活動如下:

Intent intent = new Intent(this, HomeActivity.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // this will clear all the stack 
intent.putExtra("Exit me", true); 
startActivity(intent); 
finish(); 

然後在HomeActivity onCreate()方法添加此完成在MainActivity

setContentView(R.layout.main_layout); 

if(getIntent().getBooleanExtra("Exit me", false)){ 
    finish(); 
    return; // add this to prevent from doing unnecessary stuffs 
} 
10

這很適合我。

  • 你應該使用FLAG_ACTIVITY_CLEAR_TASKFLAG_ACTIVITY_NEW_TASK標誌。

    Intent intent = new Intent(SecondActivity.this, CloseActivity.class); 
    //Clear all activities and start new task 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); 
    startActivity(intent); 
    
  • onCreate()CloseActivity活性的方法。

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        finish(); // Exit 
    } 
    
+0

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);爲我工作。 –

0
public void onBackPressed() { 
    super.onBackPressed(); 
    finishAffinity(); 
    System.exit(0); 
} 

可以是這種方法是更好地利用以關閉所有的活性和清潔設備存儲器中。

0

要清除所有的活動,同時開闢新的一個然後執行以下操作:

Intent intent = new Intent(getApplicationContext(), YourActivity.class); 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent); 
0

有時finish()不工作

我已經解決了這個問題與

finishAffinity()

不要使用

System.exit(0); 

它將完成應用程序而無需註冊。

相關問題