1

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

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>

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

4

3 回答 3

2

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

于 2013-07-08T14:06:22.003 回答
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>
于 2013-07-08T14:12:08.610 回答
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>
于 2013-07-08T14:14:09.153 回答