Android - How To Override the "Back" button so it doesn't Finish() my Activity?

問題:

I currently have an Activity that when it gets displayed a Notification will also get displayed in the Notification bar.我目前有一個活動,當它顯示時,通知也將顯示在通知欄中。

This is so that when the User presses home and the Activity gets pushed to the background they can get back to the Activity via the Notification.這樣當用戶按下 home 鍵並且 Activity 被推送到後臺時,他們可以通過通知返回到 Activity。

The problem arises when a User presses the back button, my Activity gets destroyed but the Notification remains as I want the user to be able to press back but still be able to get to the Activity via the Notification.當用戶按下後退按鈕時會出現問題,我的活動被銷燬但通知仍然存在,因爲我希望用戶能夠按下後退但仍然能夠通過通知到達活動。 But when a USER tries this I get Null Pointers as its trying to start a new activity rather than bringing back the old one.但是當用戶嘗試這個時,我得到空指針,因爲它試圖開始一個新的活動而不是帶回舊的活動。

So essentially I want the Back button to act the exact same as the Home button and here is how I have tried so far:所以基本上我希望返回按鈕的行爲與主頁按鈕完全相同,這是我迄今爲止嘗試的方式:


        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)  {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                    && keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0) {
                Log.d("CDA", "onKeyDown Called");
                onBackPressed();
            }

            return super.onKeyDown(keyCode, event);
        }

        public void onBackPressed() {
            Log.d("CDA", "onBackPressed Called");
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent); 

            return;
        }   

However the above code still seems to allow my Activity to be destroyed, How can I stop my Activity from being destroyed when the back button is pressed?然而,上面的代碼似乎仍然允許我的 Activity 被銷燬,如何在按下後退按鈕時阻止我的 Activity 被銷燬?


解決方案:

參考一: https://en.stackoom.com/question/DBNM
參考二: https://stackoom.com/question/DBNM
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章