Android获取app 启动页的全类名

1.先说一下网上搜到的通用玩法 实测可用就是看着不简洁,当然获取的信息还是很全的

private String doStartApplicationWithPackageName(String packagename) {

        // 通过包名获取此APP详细信息,包括Activities、services、versioncode、name等等
        PackageInfo packageinfo = null;
        try {
            packageinfo = mContext.getPackageManager().getPackageInfo(packagename, 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageinfo == null) {
            return null;
        }

        // 创建一个类别为CATEGORY_LAUNCHER的该包名的Intent
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(packageinfo.packageName);

        // 通过getPackageManager()的queryIntentActivities方法遍历
        List resolveinfoList = mContext.getPackageManager()
                .queryIntentActivities(resolveIntent, 0);
        for (ResolveInfo resolveInfo : resolveinfoList) {
            Log.d(TAG, "resolveInfo:" + resolveInfo);
        }
        ResolveInfo resolveinfo = resolveinfoList.iterator().next();
        if (resolveinfo != null) {
            // packagename = 参数packname
            String packageName = resolveinfo.activityInfo.packageName;
            // 这个就是我们要找的该APP的LAUNCHER的Activity[组织形式:packagename.mainActivityname]
            String className = resolveinfo.activityInfo.name;
            return className;
        }
        return null;
    }

2.ComponentName 可以启动其他应用的Activity、Service,其中包含对应组件的包名全类名

ComponentName chatActivity =new ComponentName("com.npf.chat", "com.npf.chat.ui.ChatActivity"); 
Intent intent =new Intent(); 
intent.setComponent(chatActivity); 
startActivity(intent);

resolveActivity 用于启动Activity前判断对应Activity是否存在的
结合起来

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setPackage(getPackageName());//pkg为包名
ComponentName componentName = intent.resolveActivity(getPackageManager());
Log.d("MainActivity", "componentName:" + componentName);

打印截图如下


2018-03-28_152029.png

ok,基本是妥了,说一下注意事项,此处获取方法就类似Intent的隐式跳转,基本隐式跳转能ok获取到的全类名也就妥妥的,众所周知的Intent跳转会默认添加
intent.addCategory(Intent.CATEGORY_DEFAULT)
同理,此处Manifest对应的Activity如果没有添加

同样的代码打印如下

2018-03-28_152743.png

此时隐式跳转直接崩溃报错

Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=aa pkg=com.lei.simpletest }
        Intent launchIntentForPackage = getPackageManager().getLaunchIntentForPackage(getPackageName());
        ComponentName component = launchIntentForPackage.getComponent();
        Log.d("MainActivity", "component:" + component);
MainActivity: component:ComponentInfo{com.lei.simpletest/com.lei.simpletest.MainActivity}

特此记录...

你可能感兴趣的:(Android获取app 启动页的全类名)