Get all activities' names from an explicit external application

时间:2019-01-09 22:04:17

标签: android android-studio android-activity

My code so far:

    val  listofApps:List<ApplicationInfo> = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
    var test: Array<ActivityInfo>
    try{
        test = packageManager.getPackageInfo(listofApps.get(2).packageName, PackageManager.GET_ACTIVITIES).activities
        var s: String = "App " + listofApps.get(2).packageName + " has activities: "
        for (activityInfo in test) {
            s = s + activityInfo.name + " "
        }
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
    }catch (e:Exception){
        Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
    }

I get an exception because test is null. If I use context.packageName instead of listOfApps.get(2) it works as expected. I did not include the external app in the manifest, but since I will do this with all the apps installed on the phone, there might be new apps at some time I can't declare them, so I need a more dynamic solution.

How can I fix the code so I can get all activities from the app ?

1 个答案:

答案 0 :(得分:0)

Edited based on your comments:

I believe that's happening because getInstalledApplications will also return the package name of services that don't have any activities.

You first need to iterate over the list and then check if the package itself has any activity or not:

val installedApplications:List<ApplicationInfo> = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
    var packageInfo: PackageInfo?
    var activities: Array<ActivityInfo>

    try{
        for (activity in installedApplications) {
            packageInfo = packageManager.getPackageInfo(activity.packageName, PackageManager.GET_ACTIVITIES)
            if (packageInfo.activities != null) {
                activities = packageInfo.activities

                var result: String = "App " + activity.packageName + " has activities: "
                for (activityInfo in activities) {
                    result = result + activityInfo.name + " "
                }

                Log.d(TAG, result)
            }
        }

    } catch (e:Exception){
        Log.e(TAG, "${e.message}")
    }