不调用广播接收器

时间:2013-07-08 13:54:47

标签: android performance android-layout android-intent

在我的片段中,我有一个按钮,当按下按钮时,我按照以下方式广播自定义意图:

package com.my.store.fragments.shopping;

public class ShoppingFragment extends Fragment{
    ...
    @Override
    public void onStart(){
       super.onStart()

       myButton.setOnClickListener(new OnClickListener(){
             @Override
             public void onClick(View v){
                broadcastMyIntent(v);
             }
       });
    }

    public void broadcastMyIntent(View view){
     Intent intent = new Intent();
     intent.setAction("com.my.store.fragments.shopping.CUSTOM_INTENT");
     getActivity().sendBroadcast(intent);
    }
}

然后,我定义了一个广播接收器:

package com.my.store.utils;

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Receive my intent", Toast.LENGTH_LONG).show();
    }
}

我在 AndroidManifest.xml

中注册接收器
<application
    ...>
    <activity ...>
       ...
    </activity>

    <!--this is the receiver which doesn't work-->
    <receiver android:name="com.my.store.utils.MyReceiver"> 
          <action android:name="com.my.store.fragments.shopping.CUSTOM_INTENT"/>
    </receiver>

    <!--I have another receiver here, it is working fine-->
   <receiver android:name="com.my.store.utils.AnotherReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
        </intent-filter>
    </receiver>
</application>

我运行我的应用程序,当我按下按钮时,我的接收器没有被调用。为什么呢?

3 个答案:

答案 0 :(得分:2)

您忘记用<action>容器包围<intent-filter>元素。

答案 1 :(得分:0)

<强>的AndroidManifest.xml

<!--this is the receiver which doesn't work-->
<receiver android:name="com.my.store.utils.MyReceiver"> 
  <intent-filter>
   <action android:name="com.my.store.fragments.shopping.CUSTOM_INTENT"/>
  </intent-filter>
</receiver>

答案 2 :(得分:0)

试试这个

<receiver android:name="com.my.store.utils.MyReceiver"> 
   <intent-filter>
      <action android:name="com.my.store.fragments.shopping.CUSTOM_INTENT"/>
      <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</receiver>