获取android应用的launcher Activity名称

bqf10yzr  于 2023-04-10  发布在  Android
关注(0)|答案(4)|浏览(172)

我需要获取启动器活动的名称,以便从我的应用程序启动该活动。任何解决方案

dgenwo3n

dgenwo3n1#

晚,但更好的方式,它会给予确切的意图,推出一项活动

PackageManager pm = getPackageManager();
Intent intent=pm.getLaunchIntentForPackage(pacakgeName);
startActivity(intent);
rjee0c15

rjee0c152#

使用以下代码获取所有包的启动器Activity:

final PackageManager pm = getPackageManager();

Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

List<ResolveInfo> appList = pm.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));

for (ResolveInfo temp : appList) {
    Log.v("my logs", "package and activity name = "
            + temp.activityInfo.packageName + "    "
            + temp.activityInfo.name);
}
hfwmuf9z

hfwmuf9z3#

尽管上面的答案直接回答了OP的问题,但我想补充我的两分钱:

/** Backwards compatible method that will clear all activities in the stack. */
public void startLauncherActivity(Context context) {
    PackageManager packageManager = context.getPackageManager();
    Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
    ComponentName componentName = intent.getComponent();
    Intent mainIntent = IntentCompat.makeRestartActivityTask(componentName);
    context.startActivity(mainIntent);
}

在这里,我不仅获得了应用程序的启动器Activity,而且还清除了所有Activity的backstack(这是我触发启动器Activity时实际需要的)。例如,我在过期的auth token情况下调用它。
重要的是使用IntentCompat,否则必须求助于Intent标志Intent.FLAG_ACTIVITY_CLEAR_TASK,该标志仅在API 11中引入。

oiopk7p5

oiopk7p54#

这是你能用的最简单的解决方法,而且效果很好。

private String getLauncherActivityName(){
        String activityName = "";
        final PackageManager pm = getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(getPackageName());
        List<ResolveInfo> activityList = pm.queryIntentActivities(intent,0);
        if(activityList != null){
            activityName = activityList.get(0).activityInfo.name;
        }
        return activityName;
    }

相关问题