LocalBroadcastManager无法按预期工作

时间:2014-11-20 04:50:53

标签: android broadcastreceiver localbroadcastmanager

在我的应用程序中,我必须从IntentService类通知我的Activity。 为此我使用的是LocalBroadcastManager。但是我的广播接收器的onReceive没有收到任何东西。这是我写的。

在我的BaseActivity中,我已经注册了我的接收器。

public class BaseActivity extends FragmentActivity implements App {

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
}

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter(custom-event-name));
}

@Override
protected void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(
            mMessageReceiver);
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        System.out.println("Overlay Message" +bundle.getString("message"));
          }
      };
  }

我从RegisterAlarmIntentService类发送本地广播。

  public class RegisterAlramIntentService extends WakefulIntentService implements
           APIConstants {

    public RegisterAlramIntentService() {
        super("AlarmService");
   }

    @Override
   public String getTag() {
        return "AlarmService";
   }

@Override
protected void onHandleIntent(Intent intent) {
            System.out.println("Working till here fine In RegisterAlarm");
            Bundle bundle = intent.getExtras();
            Intent localIntent = new Intent(custom-event-name);
            localIntent.putExtras(bundle );
            LocalBroadcastManager.getInstance(this).sendBroadcast(
                        localIntent);


      }
  }

调用onHandleIntent()方法。但是接收器的onReceive()没有收到任何东西。 请帮忙。在此先感谢!!

1 个答案:

答案 0 :(得分:2)

尝试

 public class RegisterAlramIntentService extends WakefulIntentService implements
           APIConstants {

   Intent localIntent;

    public RegisterAlramIntentService() {
        super("AlarmService");

       localIntent = new Intent(custom-event-name);
   }

    @Override
   public String getTag() {
        return "AlarmService";
   }

@Override
protected void onHandleIntent(Intent intent) {
            System.out.println("Working till here fine In RegisterAlarm");
            Bundle bundle = intent.getExtras();
            Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
            localIntent.putExtras(bundle );
            LocalBroadcastManager.getInstance(this).sendBroadcast(
                        localIntent);


      }
  }

同样在清单中:

<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>

请参阅this