0

發出的廣播我已經從Service,我發送一個廣播intentBroadcastReceiver,然後這個廣播接收器發送回的Service內指定的BroadcastReceiver廣播接收器的的onReceive()未能接收由另一廣播接收器

下面的代碼:

private Notification getNotificationAU() { 
     mBuilder = 
       new NotificationCompat.Builder(getBaseContext()) 
         .setSmallIcon(R.mipmap.app_icon_1) 
         .setContentTitle("title") 
         .setContentText(***); 

     // for action button 
     Intent actionIntent = new Intent(getBaseContext(), BroadcastSender.class); 
     PendingIntent actionPendingIntent = PendingIntent 
       .getBroadcast(getBaseContext(), 
         0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

     mBuilder.setAutoCancel(true); 
     mBuilder.addAction(***, "***", actionPendingIntent); 
     return mBuilder.build(); 
    } 

這裏的BroadcastSender.class代碼:

public class BroadcastSender extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 

     Toast.makeText(context, "Broadcast Received by BroadcastSender", Toast.LENGTH_SHORT).show(); 

     // send back to your class 
     Intent newIntent = new Intent(); 
     newIntent.setAction(context.getString(R.string.broadcast_id)); 
     context.sendBroadcast(newIntent); 
     context.sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); 
     Toast.makeText(context, "Broadcast sent back.", Toast.LENGTH_SHORT).show(); 

    } 
} 

兩者Toasts以上是越來越所示。

這裏的BroadcastReceiverService內:

public class MyBroadcastReceiver extends BroadcastReceiver { 

     public MyBroadcastReceiver(){ 
      super(); 
     } 

     @Override public void onReceive(Context context, Intent intent) { 

      Toast.makeText(context, "onReceive() in service called", Toast.LENGTH_SHORT).show(); 

     if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id_2))) { 
       ... 
       ... 
       ... 
     } else if (intent.getAction() != null && intent.getAction().equals(getString(R.string.broadcast_id))) { 

       // perform the task 

     } else { 
       Toast.makeText(context, "Intent is null.", Toast.LENGTH_SHORT).show(); 
     } 
     } 
    } 

這裏是strings.xml

<string name="broadcast_id">***</string> 

這裏的AndroidManifest.xml

<receiver android:name=".BroadcastSender"/> 

的問題是MyBroadcastReceiver即使在兩個節點都具有相同的廣播ID R.string.broadcast_id時也沒有收到任何廣播。

爲什麼它沒有收到BroadcastSender.class發送的廣播?

請讓我知道。

+1

如何註冊和取消註冊廣播接收器?您是否可以顯示代碼 –

+1

您是否也可以將註冊了MyBroadcastReceiver的代碼粘貼到您的服務中? –

+0

感謝您找出這個愚蠢的錯誤!我忘了在註冊廣播接收器時添加'myIntentFilter.addAction(getString(R.string.broadcast_id));'。它現在有效! –

回答

0

這裏的問題是在註冊BroadcastReceiver時未添加行myIntentFilter.addAction(getString(R.string.broadcast_id));

添加該行後就解決了。

感謝Jitesh MohiteHasif Seyd幫助我找出這個小而嚴重的錯誤。