【问题标题】:Get all activities' names from an explicit external application从显式外部应用程序获取所有活动的名称
【发布时间】:2019-06-04 18:07:19
【问题描述】:

到目前为止我的代码:

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

我得到一个异常,因为 test 为空。如果我使用 context.packageName 而不是 listOfApps.get(2) 它会按预期工作。我没有在清单中包含外部应用程序,但由于我将使用手机上安装的所有应用程序执行此操作,因此有时可能会有新应用程序我无法声明它们,因此我需要一个更动态解决方案

如何修复代码以便从应用中获取所有活动?

【问题讨论】:

    标签: android android-studio android-activity


    【解决方案1】:

    根据您的 cmets 进行编辑:

    我相信这是因为 getInstalledApplications 还会返回没有任何活动的服务的包名称。

    您首先需要遍历列表,然后检查包本身是否有任何活动:

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

    【讨论】:

    • 这就是我正在做的,而不是“specific.package.name”我有 list.get(2).packageName
    • 是的,但这意味着您可以获得一个没有活动的应用程序 - 对吧?您只是在访问列表第二个元素上的应用程序。你不应该迭代 listofApps 吗?
    • 我想我已经理解了这个问题 - 你所拥有的 null 不在服务上?在模拟器上它说它是:com.google.android.ext.services
    • 基于此更新了我的评论。
    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 2013-01-01
    • 2011-04-21
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2019-06-11
    相关资源
    最近更新 更多