X
X
xaiponews2020-11-07 19:40:28
Android
xaiponews, 2020-11-07 19:40:28

How to limit the number of open activities?

There is an application in which new activities are opened, old activities continue to occupy memory. It is necessary to limit the maximum number of open (for example, up to 4) activities.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward, 2020-11-07
@evsmusic

In its simplest form, you can do something like this:

fun runNewActivity() {

  val am: ActivityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
  var numActivities = 0
  numActivities = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          val tasks = am.appTasks
          tasks[0].taskInfo.numActivities
      } else {
          am.getRunningTasks(10)[0].numActivities
  }

  if(numActivities > 4) {
      startActivity(...)
      // https://developer.android.com/reference/android/app/Activity#finishAffinity()
      finishAffinity()
  }
}

PS: I omitted checks for boundaries intentionally for clarity

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question