Android 以编程方式从包名称中获取 Activity with intentfilter 启动器

Android get Activity with intentfilter launcher from package name programatically

我从第三方应用程序中获得了这个包名:

"com.example.packagename"

此应用程序有一个 activity,其 intentFilter 的启动器类别为:

<category android:name="android.intent.category.LAUNCHER"/>

如何以编程方式从包名称中检索此 activity 名称?

正在寻找第三方 Termux 应用程序的 laucher activity(程序包名称:"com.termux")。

片段:方法 1

如果您想要 activity 名称 和组件名称,

String packageName =  "com.termux";
Intent i= getPackageManager().getLaunchIntentForPackage(packageName);
if(i != null && i.getComponent()!=null){
    Log.i("Activity", " Activity getComponent : " +i.getComponent().toString());
    Log.i("Activity", " Activity getClassName: " +i.getComponent().getClassName());
    Log.i("Activity", " Activity getShortClassName : " +i.getComponent().getShortClassName());
} else{
    Log.i("Activity", " Activity not found");
}

输出:

Activity getComponent : ComponentInfo{com.termux/com.termux.app.TermuxActivity}
Activity getClassName: com.termux.app.TermuxActivity
Activity getShortClassName : .app.TermuxActivity

片段::方法 2

PackageManager pm = getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage("com.termux");
List<ResolveInfo> activityList = pm.queryIntentActivities(intent, 0);
Collections.sort(activityList, new ResolveInfo.DisplayNameComparator(pm));

for (ResolveInfo temp : activityList) {
    Log.i("Activity", " Activity :  " +temp.activityInfo.name);

}

输出:

Activity:  Activity :  com.termux.app.TermuxActivity

注:

如果您想启动一个包的启动器activity

String packageName =  "com.termux";
Intent i = getPackageManager().getLaunchIntentForPackage(packageName);
if(i != null){
    startActivity(i);
} else{
    Log.i("Activity", "package not found, ensure the "+packageName+" is installed.");
}

如果您想从启动器activity名称中查找包名称,

String activityName = "TermuxActivity";

PackageManager pm = getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> activityList = pm.queryIntentActivities(intent, 0);
Collections.sort(activityList, new ResolveInfo.DisplayNameComparator(pm));
for (ResolveInfo temp : activityList) {
    if(temp.activityInfo.name.endsWith(activityName)){
        Log.i("ActivityCheck", " Activity : " +temp.activityInfo.name+ " package name: " +temp.activityInfo.packageName);
    }
}

输出:

ActivityCheck:  Activity : com.termux.app.TermuxActivity package name: com.termux