我註冊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
(開始,並且尚未destoryed)不能接收廣播。
如果我的receiver
變量更改爲擴展BroadcastReceiver
,並且已經被證明可行一MyReceiver
類, 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");
}
}
============編輯========== ======
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>
不起作用。
首先:你需要什麼接收器? – pskink
'MyService'需要接收來自通知操作的廣播。我開始讓'MainActivity'發送廣播。 – Erwai
一個通知可以開始:1)活動2)廣播3)服務,所以直接使用選項#3 – pskink