未调用广播接收器



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

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>

我运行我的应用程序,当我按下按钮时,我的接收器不会被呼叫。为什么?

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

试试这个

<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>

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>

最新更新