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

use*_*239 76 android cross-application start-activity

我的应用程序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>
Run Code Online (Sandbox Code Playgroud)

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

use*_*239 143

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

android:exported="true"
Run Code Online (Sandbox Code Playgroud)

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

finish();
Run Code Online (Sandbox Code Playgroud)

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

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

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.example", "com.example.MyExampleActivity"));
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

您还可以使用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();
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)

  • @JackWM将android:exported ="true"添加到您的活动属性中 (10认同)
  • @JackWM如果您尝试启动的活动具有意图过滤器,它也会起作用.这是因为当存在intent过滤器时,`android:exported` XML属性的默认值为"true". (3认同)
  • 嗯,不适合我.我有两个应用程序,每个应用程序有一个活动:`com.examplea.MainActivityA`和`com.exampleb.MainActivityB`.从MainActivityA我运行您的代码片段,使用字符串"com.exampleb"和"com.exampleb.MainActivityB".但是,我只是得到`android.content.ActivityNotFoundException:无法找到显式活动类{com.exampleb/com.exampleb.MainActivityB}; 你有没有在AndroidManifest.xml中声明这个活动?` (2认同)

aze*_*lez 17

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

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • 您不需要两个应用程序都具有相同的签名.例如,您可以使用以下方法启动Google地图:Intent i = getPackageManager().getLaunchIntentForPackage("com.google.android.apps.maps"); (7认同)