用于显式启动外部应用的代码

时间:2011-05-09 17:37:32

标签: android

从我的一个应用程序中,我正在尝试启动另一个应用程序。我想使用明确的意图。

ComponentName cn = new ComponentName("com.myOtherApp", "OtherAppActivity");
Intent intent = new Intent();
intent.setComponent(cn);
context.startActivity(intent);

然而,当我运行该代码时,它会询问我是否在清单中声明了该活动。但是,当我将以下内容放入清单时,我得到了同样的错误:

<activity android:name="com.myOtherApp.OtherAppActivity">
</activity>

我做错了什么?

由于

6 个答案:

答案 0 :(得分:25)

尝试这样的事情......

在'myOtherApp'的清单中,使用具有公司特定意图的'OtherAppActivity'的意图过滤器,例如......

<activity
    android:name=".OtherAppActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="com.mycompany.DO_SOMETHING" />
    </intent-filter>
</activity>

然后,在“通话”应用中,使用...

Intent intent = new Intent();
intent.setAction("com.mycompany.DO_SOMETHING");
context.startActivity(intent);

答案 1 :(得分:19)

我遇到了这个问题并搜索了几个小时寻找解决方案。终于找到了它:http://www.krvarma.com/2010/08/launching-external-applications-in-android。该链接显示了如何使用包管理器启动您只拥有包名称的任何应用程序:

PackageManager pm = this.getPackageManager();

try
{
  Intent it = pm.getLaunchIntentForPackage(sName);

  if (null != it)
    this.startActivity(it);
}

catch (ActivityNotFoundException e)
{
}

答案 2 :(得分:17)

您需要在新ComponentName的第二个参数中指定完全限定的类名,如下所示:

ComponentName cn = new ComponentName("com.myOtherApp", "com.myOtherApp.OtherAppActivity");

我认为这是因为清单中的包名称和活动名称不一定必须具有相同的包路径,因此新的ComponentName调用不会推断类名称第二个参数以包名称为前缀第一个参数。

答案 3 :(得分:0)

除了@Sogger回答要记住的事情是你的接收器类是com.myOtherApp.receiver.OtherAppActivity和AndroidManifest中提到的包是com.myOtherApp你的代码将是

ComponentName cn = new ComponentName("com.myOtherApp", "com.myOtherApp.receiver.OtherAppActivity");

答案 4 :(得分:0)

从API23开始,您可以使用方法ComponentName.createRelative(String pkg, String cls)并执行:

ComponentName cn = new ComponentName(ComponentName.createRelative("com.myOtherApp", ".OtherAppActivity"));
Intent intent = new Intent();
intent.setComponent(cn);
context.startActivity(intent);

这样,您可以使用相对类路径创建ComponentName对象。注意类路径开头的点。有必要指出该方法应将第二个参数视为相对路径。正如@Sogger所提到的,ComponentName构造函数将class参数约束为绝对路径。

另请注意,通过这种方式,您使用显式意图,而不必向目标活动插入任何其他意图过滤器。

答案 5 :(得分:-1)

将意图创建为 action.Main ,并将启动器类别添加到其中:

Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
相关问题