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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章