Android通过程序包名称通过intentfilter启动器从程序名获取Activity

时间:2019-04-30 14:55:59

标签: android android-activity package

我有一个第三方应用程序提供的软件包名称:

"com.example.packagename"

该应用程序的活动带有一个带有类别Launcher的intentFilter:

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

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

1 个答案:

答案 0 :(得分:2)

查找第三方Termux应用程序(程序包名称:“ com.termux”)的启动活动。

代码段:方法1

如果要活动名称和组件名称,

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

注意:

如果您要启动程序包的启动器活动

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

如果您要从启动器活动中找到包名称,请

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