Android以编程方式从包名称获取具有intent过滤器启动器的Activity

问题描述 投票:1回答:1

我从第三方应用程序获得此包名称:

"com.example.packagename"

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

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

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

android android-activity package android-package-managers
1个回答
2
投票

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

Snipplet:方法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

Snipplet ::方法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

注意:

如果要启动程序包的Launcher活动,

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

如果要从Launcher活动名称中查找包名称,

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
© www.soinside.com 2019 - 2024. All rights reserved.