我在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>
不起作用。
答案 0 :(得分:0)
这看起来像一个明显的问题,
请确保您在清单中声明接收器! 例如:
{{1}}