Home > Blockchain >  Kotlin list all activities at runtime
Kotlin list all activities at runtime

Time:12-28

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 succesfully when an item is touched.

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

CodePudding user response:

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) {
            }
        }

CodePudding user response:

You can get a list of all activities using this code

getActivity()
  .getPackageManager()
  .getPackageInfo(getActivity().getPackageName(), PackageManager.GET_ACTIVITIES)
  .activities

Edit - getActivity() can be replaced by this when calling from activity else when calling from fragment getActivity() will be required.

  • Related