Closing All Activities and Launching Any Specific Activity

Often times, most apps have an option where all the activities of the current app are closed and any new specific activity is launched. For example, on logging out of the application, all the activities are closed and login activity is started to allow user to make any new session.



This can be done using few lines code with power of intents like this:

Kotlin

  val i = Intent(applicationContext, SplashActivity::class.java)        // Specify any activity here e.g. home or splash or login etc
  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
  i.putExtra("EXIT", true)
  startActivity(i)
  finish()

Java

  Intent i = new Intent(applicationContext, SplashActivity.java);        // Specify any activity here e.g. home or splash or login etc
  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  i.putExtra("EXIT", true);
  startActivity(i);
  finish();


If you liked this article, you can read my new articles below:


Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan