设置数据时广播接收器未接收广播

时间:2014-06-05 14:40:09

标签: android broadcastreceiver intentfilter

我有两个应用程序,第二个应用程序在manifest.xml中声明了广播接收器

    <receiver android:name="com.company.app2.MyBroadcastReceiver" >
        <intent-filter>
            <action android:name="com.company.ACTION_CUSTOM" />
            <category android:name="android.intent.category.DEFAULT" /> 
        </intent-filter>
    </receiver>

从另一个应用程序我以这种方式发送广播

Intent intent = new Intent();
intent.setAction("com.company.ACTION_CUSTOM");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//if I decomment the next line the BroadcastReceiver will not receive the broadcast 
//intent.setData(fileUri);

请大家告诉我为什么我在设置数据时无法收到广播...谢谢!

2 个答案:

答案 0 :(得分:0)

来自文档:

  

提供的数据类型通常由意图的行为决定。例如,如果操作是ACTION_EDIT,则数据应包含要编辑的文档的URI。

所以在你的情况下,你可以简单地通过额外的意图传递uri。

答案 1 :(得分:0)

当找到隐式意图的匹配组件时,将使用操作,类别,数据和类型,即所有必须匹配。

这意味着仅使用 操作的意图将仅与具有操作的接收者匹配,而具有操作数据的意图仅匹配具有该操作的接收者action 与数据URI匹配的<data>元素。

请注意,额外内容永远不会用于匹配,这就是为什么当您将数据作为额外内容而非使用setData()时,您确实匹配了仅限操作的接收器。

示例:

Intent intent = new Intent();
intent.setAction("com.company.ACTION_CUSTOM");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("file://somefile.jpg"));

这将使接收器与以下意图过滤器匹配:

<receiver android:name="com.company.app2.MyBroadcastReceiver" >
    <intent-filter>
        <action android:name="com.company.ACTION_CUSTOM" />
        <category android:name="android.intent.category.DEFAULT" /> 
        <data android:scheme="file" />
    </intent-filter>
</receiver>

...因为动作,类别和数据都匹配。 如果intent过滤器没有任何<data>元素,它只会匹配也没有任何数据的意图。

使用自定义操作跳过意图数据是很常见的,特别是如果仅在应用内部使用。但是,对于使用标准操作(例如android.intent.action.VIEW)的意图,数据(或类型)对于进行任何合理匹配至关重要(如果android.intent.action.VIEW意图与图像URI作为数据匹配,则想象混乱所有支持android.intent.action.VIEW的组件,无论数据类型如何!)

相关问题