如何在另一个应用程序中启动活动?

时间:2010-02-05 18:46:59

标签: android start-activity cross-application

我的应用程序A定义如下:

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name="com.example.MyExampleActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

现在在应用程序B中,如何编写代码来启动应用程序A中的活动?谢谢!

2 个答案:

答案 0 :(得分:135)

如果你们面临“权限拒绝:启动意图...”错误或者应用程序在启动应用程序时没有任何理由而崩溃 - 那么在Manifest中使用此单行代码

android:exported="true"

请小心完成(); ,如果你错过了应用程序被冻结。如果它提到应用程序将是一个光滑的发射器。

finish();

另一个解决方案仅适用于同一应用程序中的两个活动。在我的例子中,应用程序B不知道代码中的类com.example.MyExampleActivity.class,因此编译将失败。

我在网上搜索并发现下面的内容,效果很好。

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);

您还可以使用setClassName方法:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.hotfoot.rapid.adani.wheeler.android", "com.hotfoot.rapid.adani.wheeler.android.view.activities.MainActivity");
startActivity(intent);
finish();

您还可以将值从一个应用传递到另一个应用:

Intent launchIntent = getApplicationContext().getPackageManager().getLaunchIntentForPackage("com.hotfoot.rapid.adani.wheeler.android.LoginActivity");
if (launchIntent != null) {
    launchIntent.putExtra("AppID", "MY-CHILD-APP1");
    launchIntent.putExtra("UserID", "MY-APP");
    launchIntent.putExtra("Password", "MY-PASSWORD");
    startActivity(launchIntent);
    finish();
} else {
    Toast.makeText(getApplicationContext(), " launch Intent not available", Toast.LENGTH_SHORT).show();
}

答案 1 :(得分:15)

如果两个应用程序具有相同的签名(意味着两个APPS都是您的,并使用相同的密钥签名),您可以按如下方式调用其他应用程序活动:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

希望它有所帮助。

相关问题