[英]How to NOT end the application when Back button is pressed
我正在構建一個具有3個屏幕的應用程序; 第一個是啟動屏幕,第二個是我需要用戶始終顯示的位置,第三個是用於設置某些內容的位置。
當我在第二個屏幕上並且按android上的“后退”按鈕時,應用程序結束。 同樣,當我通過點擊其圖標啟動應用程序時,它從頭開始。 我不要那個。
我只想讓應用程序僅在用戶通過轉到android中的應用程序管理器自行結束時才結束。 即使應用程序正在運行,並且用戶單擊了應用程序圖標,它也應該轉到當前正在運行的屏幕,而不是重新啟動它。
最好的祝福
只需在第二個活動上覆蓋“ onBackPressed”方法
@Override
public void onBackPressed() {
//empty body
}
例如,一種替代方法是在每個活動的SharedPreferences上存儲狀態。 在開始活動的onCreate方法上,您將類似的內容放在所有內容之前:
onCreate() {
final String status = sharedPreferences.getStatus();
if("secondScreen".equals(status)) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
finish();
} else if("thirdScreen".equals(status)) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
finish();
}
//at this point your status it should be the first screen; so go on normally
setContentView();
...
為了在用戶每次啟動您的應用程序時使用相同的應用程序實例,請在AndroidManifest.xml中修改活動聲明:
<activity .... android:launchMode="singleInstance" ...>
要不退出后退按鈕,請在您的活動中覆蓋onBackPressed:
public void onBackPressed () {
// do not call super.onBackPressed();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.