Search code examples
androidkotlinandroid-activityandroid-recyclerview

Kotlin list all activities at runtime


I'm trying to make a simple debug activity that allows me to start any activity of my project at runtime.

As of right now, I've implemented a RecyclerView which gets its data from a list, in such fashion:

    val activitiesList = ArrayList<Activity>()
    activitiesList.add(FrameHomeActivity())
    activitiesList.add(LeaderHomeActivity())
    activitiesList.add(LoginActivity())
    ...

but this relies on me having to manually update this list when adding a new activity.

I've already managed to attach a clickListener to the RecyclerView, so that each activity can start successfully when an item is touched.

Is there a way to get all the activities in the project "dynamically", so that I don't have to update this code each time a new activity is added?


Solution

  • You don't call constructor of an Activity instead you fire an Intent . You get the Activity from PackageManager then you start it by name.

    val activities = packageManager
            .getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).activities
        val nameList= activities.map { it.name }
    

    nameList here is List<String> it will contains fully qualified name of your Activity classes . You can use this name to create an Intent to start the activity from adapter.

    fun onClickItem(context:Context, activityName:String){
                try {
                    val c = Class.forName(activityName)
                    val intent = Intent(context, c)
                    context.startActivity(intent)
                } catch (ex: Exception) {
                }
            }