【问题标题】:Android: Starting An Activity For A Different Third Party AppAndroid:为不同的第三方应用程序启动 Activity
【发布时间】:2010-08-19 03:00:55
【问题描述】:

我正在开发一个应用程序,我想将 Last.fm 应用程序集成到其中。基本上,当有人在我的应用程序中查看艺术家时,我希望有一个按钮,他们可以点击该按钮以打开带有艺术家信息的 Last.fm 应用程序。

此意图有效,但它会加载一个菜单,询问我想使用哪个应用程序(浏览器或 Last.fm):

Intent i = new Intent();
i.setData(Uri.parse("http://last.fm/music/" + headliner));
i.setAction("android.intent.action.VIEW");
startActivity(i);

但是,我只想启动 Last.fm 应用程序并跳过询问要使用哪个应用程序的对话框,我想也许使用 setPackage() 方法会像这样工作:

i.setPackage("fm.last.android");

但它会导致应用崩溃:

android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=http://last.fm/music/Rihanna pkg=fm.last.android }

是否可以只启动 Last.fm 应用程序? Here'sLast.fm 的 AndroidManifest.xml 副本供参考。

感谢阅读, 托尼

【问题讨论】:

    标签: android android-intent


    【解决方案1】:

    是的,这是可能的,但您需要知道正确的组件名称。定期启动 last.fm 应用程序并检查日志文件中的 cmp=... 应用程序启动时使用的信息。然后在您的应用中使用它。

    我从我的应用程序中从市场启动 Z-DeviceTest 应用程序,没有出现这样的问题:

    final Intent intentDeviceTest = new Intent("android.intent.action.MAIN");                
    intentDeviceTest.setComponent(new  ComponentName("zausan.zdevicetest","zausan.zdevicetest.zdevicetest"));
    startActivity(intentDeviceTest);
    

    就我而言,我从 logcat 获取的信息是:

    // dat=content://applications/applications/zausan.zdevicetest/zausan.zdevicetest.zdevicetest

    // cmp=zausan.zdevicetest/.zdevicetest

    为了知道如何使用正确的组件/类启动应用程序...对 last.fm 应用程序执行相同的操作

    编辑: 我已经测试过从我自己的应用程序启动 Last.fm,这可以正常工作,没有任何错误:

    final Intent intentDeviceTest = new Intent("android.intent.action.MAIN");                
    intentDeviceTest.setComponent(new ComponentName("fm.last.android","fm.last.android.LastFm"));
    startActivity(intentDeviceTest);
    

    【讨论】:

    • 这是一个 hack,不被认为是调用应用程序的正确方法。这是确保出现各种错误的可靠方法
    • 你能解释一下为什么这是一个 hack 吗?您正在使用应用程序启动器调用的应用程序的常规意图,即当您单击主屏幕上的应用程序图标时?无论如何,那么您建议的正确方法是什么?
    • 也许我理解错了。如果您正在调用启动器调用的活动,那么我想应该没问题。我将这个问题理解为调用不同包的内部活动。这很容易中断,因为该活动可能需要可能导致崩溃或类似情况的额外意图。没有看到代码,就无法判断它是否 100% 安全
    • @Brent Foust,文档实际上建议这样做 if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } 以避免 ActivityNotFound 异常。
    • @The_Martian 听起来也不错。就“推荐”的 Android 方式而言,阅读所有错误处理可能会非常混乱,只是为了启动一个活动。如果常见的情况是它会成功,那么 try/catch 会读取得更清楚一些。 +1 提及此替代方案。
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多