Search code examples
androidbroadcastreceiverintentfilterintentservicelocalbroadcastmanager

Cannot using BroadcastReceiver with LocalBroadcastManager


I have 1 activity and 1 service. The service will be started when the activity comes into background and will be stopped when the activity comes into foreground. When the service stops, I want to send an object from it to the activity by intent. Here is my code

MyActivity.java

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_WITH_RLM)) {                
        //I will get the object received by service here 
        }
    }
};

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_record_lesson_ins);

    localBroadcastManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ACTION_WITH_RLM);
    localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}

@Override
protected void onResume() {
    super.onResume();
    if (intent != null) {
        stopService(intent);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (intent != null) {
        startService(intent);
    }
}

@Override
protected void onStop() {
    super.onStop();
    localBroadcastManager.unregisterReceiver(broadcastReceiver);
}

MyService.java

private RecordLessonModel recordLessonModel;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //I code sth for handle recordLessonModel object
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    Intent intent = new Intent(MyActivity.ACTION_WITH_RLM);
    intent.putExtra(MyActivity.RECORD_MODEL_NAME, Parcels.wrap(recordLessonModel));
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

The problem here is my broadcastReceiver in MyActivity cannot receive intent from service when my activity comes to foreground. I don't know why.

Thanks.


Solution

  • You should consider unregistering your broadcastReceiver into onDestory() instead of onStop()

    because your brodcastReceiver is getting unregistered when activity goes background.

    For more look at HERE