我想从我的Android应用程序启动一个已安装的包。我认为使用意图是可能的,但我没有找到一种方法来做到这一点。有没有链接,在哪里可以找到相关信息?


当前回答

从API 30 (Android 11)开始,你可以通过launchIntentForPackage接收nullpointerexception

val launchIntent: Intent? = activity.packageManager.getLaunchIntentForPackage("com.google.android.gm")
startActivity(launchIntent) 

为了避免这种情况,您需要将所需的包添加到清单中

<queries>
    <package android:name="com.google.android.gm" />
</queries>

这里是文档 https://developer.android.com/training/package-visibility

而媒体文章 https://medium.com/androiddevelopers/package-visibility-in-android-11-cc857f221cd9

其他回答

试试下面的代码:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("package_name", "Class_name"));
if (intent.resolveActivity(getPackageManager()) != null) 
{
   startActivity(intent);
}

传递包名和你想要显示的消息,如果包没有安装;-)

void openApp(String appPackageName,String message){
    Intent launchIntent = getPackageManager().getLaunchIntentForPackage(appPackageName);
    if (launchIntent != null) {
        startActivity(launchIntent);
    } else {
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
    }
}

如果你知道数据和安装的包的反应,你只需在启动之前将这些信息添加到你的intent实例中。

如果你可以访问其他应用程序的AndroidManifest,你可以在那里看到所有需要的信息。

我找到了解决办法。在应用程序的清单文件中,我找到了包的名称:com.package.address和我想启动的主活动的名称:MainActivity 下面的代码启动这个应用程序:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.package.address","com.package.address.MainActivity"));
startActivity(intent);
// in onCreate method
String appName = "Gmail";
String packageName = "com.google.android.gm";
openApp(context, appName, packageName);

public static void openApp(Context context, String appName, String packageName) {
    if (isAppInstalled(context, packageName))
        if (isAppEnabled(context, packageName))
            context.startActivity(context.getPackageManager().getLaunchIntentForPackage(packageName));
        else Toast.makeText(context, appName + " app is not enabled.", Toast.LENGTH_SHORT).show();
    else Toast.makeText(context, appName + " app is not installed.", Toast.LENGTH_SHORT).show();
}

private static boolean isAppInstalled(Context context, String packageName) {
    PackageManager pm = context.getPackageManager();
    try {
        pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
        return true;
    } catch (PackageManager.NameNotFoundException ignored) {
    }
    return false;
}

private static boolean isAppEnabled(Context context, String packageName) {
    boolean appStatus = false;
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packageName, 0);
        if (ai != null) {
            appStatus = ai.enabled;
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return appStatus;
}