0

I periodically bring activity to the foreground. Code is below

    public   void moveToFront( ) {
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
            final ActivityManager activityManager = (ActivityManager)  getSystemService(Context.ACTIVITY_SERVICE);
            final List<ActivityManager.RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
            Log.e(TAG,"moveToFront ..recentTasks.size = "+recentTasks.size());
            for (int i = 0; i < recentTasks.size(); i++)
            {
                Log.e( TAG, "Application executed : "
                        +recentTasks.get(i).baseActivity.toShortString()
                        + "\t\t ID: "+recentTasks.get(i).id+"");
                // bring to front
                if (recentTasks.get(i).baseActivity.toShortString().indexOf("MainActivity") > -1) {
                    Log.e(TAG, "Moving   to front");
                    activityManager.moveTaskToFront(recentTasks.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);
                    return;
                }
            }
        }
    });

There are several scenarios where 'activityManager.getRunningTasks' method doesn't return taskinfo of my activity (this method is also deprecated), hence my code doesn't push activity to foreground.

1) I reviewed ActivityManager.getRunningTasks is deprecated android but I could not understand how to embed it in my above code (or how to map its fields to parameters of'activitymanager.moveTaskToFront so that I can push my activity to foreground)

2)Also, how to address the situation if above code is called from outside activity (say service) and Android has killed my activity (for low memory)

Community
  • 1
  • 1
mobileDev
  • 1,358
  • 2
  • 14
  • 34

1 Answers1

1

Set android:launchMode="singleTop" for the activity you need to bring to foreground in AndroidManifest.xml file. singleTop means, there will be only one instance of activity running at any time. So when your activity is in backgroud or killed, it will be brought to front and if it is in foreground, it will be left as such.

In moveToFront() method just open the activity with Intent as

Intent intent = new Intent(context, activity.class)
startActivity(intent)
arjun
  • 3,514
  • 4
  • 27
  • 48