【问题标题】:Check if an intent is an Activity or Service or none检查意图是活动还是服务或没有
【发布时间】:2016-08-23 21:03:51
【问题描述】:

我有一个 Intent 的 ArrayList,如何检查给定位置的 Intent 是否包含 Activity、Service 或什么都没有?

Intent intent = intents.get(id);
context.startActivityForResult(intent,1);

您将如何检查索引 id 处的意图是否可以正确地通过 startActivityForResult,它强调 Activity 类。

【问题讨论】:

    标签: android android-intent android-activity android-service


    【解决方案1】:

    这不是一个优雅的解决方案,但您可以尝试像这样获取意图的类名:

    Intent it = new Intent(ctx, AnotherActivity.class);
    it.getComponent().getClassName() // output com.package.app.MainActivity
    
    Intent it = new Intent(ctx, JustService.class);
    it.getComponent().getClassName() // output com.package.app.JustService
    

    并使用

    switch (...getClassName()) {
        case 'com.package.app.JustService' {
             //todo
        }
    }
    

    你可以使用 getShortClassName() 方法,它会输出没有默认包的类名:

    .JustService
    

    对于空意图,我会检查是否为空。

    【讨论】:

    • 对于非活动和服务,我决定检查组件是否为空
    【解决方案2】:

    如何检查给定位置的 Intent 是否包含 Activity、Service 或什么都没有?

    我将把它解释为“我怎样才能看到 Intent 可以解析到哪些组件?”。

    如果是这样,请使用 PackageManagerqueryIntentActivities()queryIntentServices()queryBroadcastReceivers()。请注意,Intent 可能无法用于任何、任何或所有这些。

    如何检查索引 id 处的意图是否可以通过 startActivityForResult 正确传递

    你没有,除了找到编写活动的开发人员并问他们“嘿,这会返回结果吗?”您可以将众所周知的返回结果的操作字符串列入白名单(例如,ACTION_PICKACTION_GET_CONTENTACTION_OPEN_DOCUMENT),但您无法知道任意活动是否会返回给定 Intent 的结果。

    【讨论】:

    • 对于非活动和服务,我决定检查组件是否为空
    • @CQM:我不知道您的Intents 来自哪里,但Intent 不必有ComponentName 仍然有效。 new Intent(Intent.ACTION_VIEW).setDataAndType(...) 没有 ComponentName,但仍然可以解析为一个活动,例如。
    • 谢谢,这很有见地。如果我的用例范围扩大并引入了故障,我会牢记这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    相关资源
    最近更新 更多