點擊back 鍵返回home,再進入APP 時重走啓動頁面

1.問題說明

在做APP優化的時候碰到了該問題。

點擊了back鍵,APP返回到手機home 界面 ,再點擊APP 圖標的時候,先進入啓動界面,然後才進入HomeActivity,這交互肯定是有問題的。

2.解決方法

官網API 查詢地址(https://www.android-doc.com/reference/android/app/Activity.html

先在啓動頁面的onCreate() 方法中調用如下代碼。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        //判斷是否是棧底,如果不是,則直接finish
        if (!isTaskRoot()) {
            finish();
            return;
        }
        super.onCreate(savedInstanceState);
        Log.i("StartActivity","onCreate");
        setContentView(R.layout.activity_start);
    }
isTaskRoot()方法官網說明:
Return whether this activity is the root of a task. 返回此活動是否是任務的根。

然後在你的homeActivity 中 的 onKeyDown() 方法中添加如下判斷。如果你在homeActivity 中有添加fragment ,你應該判斷一下fragment 的活動棧 ,如果棧中有fragment ,先讓棧裏面的fragment 先出棧。

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //採用moveTaskToBack 方法,當用戶點擊返回時,將APP隱藏到後臺。再次打開的時候,APP進程還存在,不打開閃屏界面 ,直接進入home 界面。
        //getSupportFragmentManager().getBackStackEntryCount() :fragment 活動棧如果不爲空,繼續走fragment 活動棧。
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN &&getSupportFragmentManager().getBackStackEntryCount()==0) {
            moveTaskToBack(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

moveTaskToBack() 方法說明:

public boolean moveTaskToBack (boolean nonRoot)

Move the task containing this activity to the back of the activity stack. The activity's order within the task is unchanged.

If false then this only works if the activity is the root of a task; if true it will work for any activity in a task.

  • 參數說明:

    參數爲false——代表只有當前activity是task根,指應用啓動的第一個activity時,纔有效;

    參數爲true——則忽略這個限制,任何activity都可以有效。

發佈了19 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章