0

我註冊BroadcastReceiverMyService廣播接收器不能接收

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> 

不起作用。

+0

首先:你需要什麼接收器? – pskink

+0

'MyService'需要接收來自通知操作的廣播。我開始讓'MainActivity'發送廣播。 – Erwai

+0

一個通知可以開始:1)活動2)廣播3)服務,所以直接使用選項#3 – pskink

回答

0

這看起來像一個清單問題,

請確保您在清單中聲明該接收器! 例如:

<receiver android:name=".receivers.BackgroundTasksReceiver"/> 
+0

後我添加'',它仍然不工作 – Erwai

+0

爲什麼不創建一個專門爲廣播接收器的新類? – JozeRi

+0

我寫我的問題,如果我使用MyReceiver',另一個'BroadcastReceiver'證明工作,'MyService '仍然沒有收到廣播。 – Erwai