Search code examples
androidandroid-activityandroid-homebutton

Redirect to particular Activity when launching app from recents


Assume you are in Activity A and press home button now your app will goto background. Now long press your home button and you can see recent's app. If I click my app it should take to particular activity not Activity A.


Solution

  • With reference of this post - How can I detect user pressing HOME key in my activity? have implemented below logic.

    Detect Home button press by using above post and store a flag in preferences. While launching app from Recent's list by first OnRestart() method will be fired so check home button pressed flag and launch particular activity.

        @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            if (isApplicationSentToBackground(this)) {
                // Do what you want to do on detecting Home Key being Pressed
                 preferences.setHomeButtonPressed(true);
            }
    
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
        // Do what you want to do on detecting app launching from recents section
            if (preferences.isHomeButtonPressed()) {
                Intent i = new Intent(this,
                        ParticularActivity.class);
                startActivity(i);
                preferences.setHomeButtonPressed(false);
            }
    
        }
    
        public static boolean isApplicationSentToBackground(final Context context) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (!topActivity.getPackageName().equals(context.getPackageName())) {
                    return true;
                }
            }
            return false;
        }