服务中的BroadcastReceiver无法接收

时间:2015-10-04 08:54:32

标签: android service broadcastreceiver android-service android-broadcast

我在BroadcastReceiver内注册MyService

public class MyService extends Service {

final static String ACTION_ONE = "one";
final static String ACTION_TWO = "two";

 BroadcastReceiver receiver;

和内部类

// use this as an inner class like here or as a top-level class
public class MyReceiver2 extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // do something
        Log.d("tag", "received! MyReceiver2");
    }

    // constructor
    public MyReceiver2(){

    }
}

onCreate方法:

@Override
public void onCreate() {
   receiver = new MyReceiver2();

    IntentFilter filter = new IntentFilter();
    filter.addAction(MyService.ACTION_ONE);
    filter.addAction(MyService.ACTION_TWO); 

    MyService.this.registerReceiver(receiver, filter);
}

以下代码在MainActivity发送广播:

    sendBroadcast.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

Intent intent = new Intent(v.getContext(), MyService.class);
            intent.setAction(MyService.ACTION_TWO);
            sendBroadcast(intent);
}
});

我无法理解为什么MyService已开始,但尚未被破坏)无法接收广播。

如果我将receiver变量更改为扩展MyReceiver且已经证明有效的BroadcastReceiver类, MyService仍未接收广播。

myReceiver = new MyReceiver();

这是MyReceiver(事实证明它运作良好):

public class MyReceiver extends BroadcastReceiver{

public MyReceiver(){
    Log.d("tag", "MyReceiver Constructor");
}

@Override
public void onReceive(Context context, Intent intent) {
        Log.d("tag", "received");
}
}

============ EDIT =====

manifest 两个

    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
        <intent-filter >
            <action android:name="one" />
            <action android:name="two" />
        </intent-filter>
    </service>

    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
    </service>

不起作用。

1 个答案:

答案 0 :(得分:0)

这看起来像一个明显的问题,

请确保您在清单中声明接收器! 例如:

{{1}}