[英]how to finish all activities and close the application in android?
我的應用程序有以下流程:
Home->screen 1->screen 2->screen 3->screen 4->screen 5>Home->screen 2->Home->Screen 3
我的問題是,當我嘗試關閉應用程序時,每次嘗試關閉應用程序時都會打開 Home 活動。
當用戶在主屏幕上按下設備的返回鍵時,我只想關閉應用程序。
有finishAffinity()方法可以完成當前活動和所有父活動,但它僅適用於Android 4.1 或更高版本。
這對我很有效。
您應該使用FLAG_ACTIVITY_CLEAR_TASK
和FLAG_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);
CloseActivity
活動的onCreate()
方法。
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); finish(); // Exit }
使用將完成當前活動和所有父活動的finishAffinity()
方法。 但它僅適用於API 16+
意味着 Android 4.1 或更高版本。
API 16+ 使用:
finishAffinity();
API 16 以下使用:
ActivityCompat.finishAffinity(this); //with v4 support library
退出整個應用程序:
finishAffinity(); // Close all activites
System.exit(0); // Releasing resources
這適用於所有版本的我。 關閉所有以前的活動,如下所示:
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
}
要在打開新活動時清除所有活動,請執行以下操作:
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
有時finish()
不起作用
我已經解決了這個問題
finishAffinity()
不要使用
System.exit(0);
它將在沒有動畫的情況下完成應用程序。
您可以嘗試使用 Intent.FLAG_ACTIVITY_CLEAR_TASK http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TASK啟動 Screen 3
嗨,如果您在片段中並且無法按原樣使用完成方法(因為完成應該可以解決您的問題),那么您可以在startActivity(intent);
之后使用getActivity.finish()
方法startActivity(intent);
. 如果您不在片段中,則可以在startActivity(intent);
后直接使用finish()
startActivity(intent);
線
在您的活動清單文件中添加android:noHistory="true"
。
有2種方法可以解決您的問題
1) 在每個活動的 startActivity(intent) 之后調用 finish()
2)在menifest文件的每個標簽中設置android:launchMode="singleInstance"
我認為第二種方式最適合解決問題,但您也可以使用第一種方式
public void onBackPressed() {
super.onBackPressed();
finishAffinity();
System.exit(0);
}
可能是這種方法更好地用於關閉所有活動和清理設備內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.