Get Current Top Activity Name in Android Kotlin code
Last updated Sep 29, 2022Activity is an Android Component where user can do interaction with the application. An android application contains multiple screen which are created by activities and these activities are maintained Activity Stack. Each screen user can only see one activity at a time which is on the top of the Activity Stack and remaining activities will go to down the stack. So How we can get the current active activity in the application. In this example we will learned how to get current top activity name.
Option 1: To get the current top activity name we will use getRunningTasks method which is declared in ActivityManager.RunningTaskInfo class, but this getRunnigTasks method is deprecated in Android API Level 21 (Lollipop), below Lollipop version we can use this method to find the current top activity name by using below code
fun checkCurrentActivity():String { try { val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val tasks: MutableList? = am.getRunningTasks(1) if (tasks != null) { if (!tasks.isEmpty()) { val topActivity = tasks[0].topActivity Log.e("topActivity","topActivity" +topActivity);
return topActivity!!.className } } } catch (ex: Exception) { ex.printStackTrace() } return "" } |
Option 2:
We have another way to get current active activity name using ActivityManager.AppTasks class which has method called appTasks method to get the list of tasks. From the list of task we will get current active activity name by using below code
fun checkCurrentActivity():String { try { val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val tasks: MutableList = am.appTasks if (tasks != null) { if (!tasks.isEmpty()) { val topActivity = tasks[0].taskInfo.topActivity Log.e("topActivity","topActivity" +topActivity); return topActivity!!.className } } Log.e("topActivity","topActivity 0000 "+tasks.isEmpty() );
} catch (ex: Exception) { ex.printStackTrace() } return "" } |
Option 3:
Get Current Running activity by ActivityLifecycleCallbacks
We can also get current running activity name by using ActivityLifeCycleCallbacks. To listen Activity LifeCycle Callbacks we need to register them on Application onCreate method
override fun onCreate() { super.onCreate() registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { currentActivity = activity } override fun onActivityStarted(activity: Activity) { currentActivity = activity } override fun onActivityResumed(activity: Activity) { currentActivity = activity Log.e("currentActivity","currentActivity "+ currentActivity!!.javaClass.name) } override fun onActivityPaused(activity: Activity) { currentActivity = null } override fun onActivityStopped(activity: Activity) { // don't clear current activity because activity may get stopped after // the new activity is resumed } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) { // don't clear current activity because activity may get destroyed after // the new activity is resumed } }) } |
The above code will trigger each activity lifecycle methods and we can find current running activity name from onActivityResumed method. Which will returns current top activity name
Sample application to get current running activity name
1. Create Simple android application
2. Create one kotlin class which contains a base class of Application. That application class will be like below
package rrtutors.com.androidtopactivity import android.app.ActivityManager import android.app.Application import android.content.Context import android.util.Log class Applications(): Application() { override fun onCreate() { super.onCreate() } fun checkCurrentActivity():String { try { val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val tasks: MutableList? = am.getRunningTasks(1) if (tasks != null) { if (!tasks.isEmpty()) { val topActivity = tasks[0].topActivity Log.e("topActivity","topActivity" +topActivity); return topActivity!!.className } } } catch (ex: Exception) { ex.printStackTrace() } return "" } } |
3. Now create two activiities and add below code in them
package rrtutors.com.androidtopactivity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import kotlinx.coroutines.delay class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) (applicationContext as Applications).checkCurrentActivity() Handler().postDelayed(Runnable { startActivity(Intent(MainActivity@this,SecondActivity::class.java)) },2000) } } |
package rrtutors.com.androidtopactivity import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) (application as Applications).checkCurrentActivity() } } |
4. Now run application and you can see the logs which will print the current running activity on the top of the activity task.
Trouble Shoots:
When we run the application it will crash and return error like "java.lang.ClassCastException: android.app.Application cannot be cast to...."
to overcome this crash we should add application name to manifest file by current create application name
android:name=".Applications" |
Keywords: Print current activity name, Get current activity name, How to get Top Activity name in the activity stack
Article Contributed By :
|
|
|
|
948 Views |