I am trying to work on a screen(say Activity A) where there is a progress bar displayed on the screen and I need to send a broadcast to a different activity(Activity B) broadcastReceiver while the progressbar is running. And if the function in the activity B is completed it will display that back to this activity A.
Now I am running progress bar in a worker thread like this and sending localbroadcast using handler(Looper.getMainLooper()):
final Context context = Activity.this.getApplicationContext();
new Thread(new Runnable() {
@Override
public void run() {
while (progressBar.getProgress() != 100) {
try {
progressBar.incrementProgressBy(2);
Thread.currentThread().sleep(100);
} catch (InterruptedException ie) {
Log.e(LOG_TAG, "Interrupted exception in progress bar: " + ie);
}
if (progressBar.getProgress() == 10) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// model is a parameter which I want to send using intents
Intent intent = new Intent("new_device");
intent.putExtra("device", model);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
});
}
}
}
}).start();
But it's not working. Broadcast is not received by the other activity. I know that Broadcast should be done on UI thread and it works fine if I do it in onResume() or onCreate() method. But when I'm using it in a handler inside a thread (inside onCreate()) it is not working.
Am I doing something wrong or is there any other way of doing it?
EDIT
I am receiving my intent in Activity B as follows:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Model model = (Model) intent.getSerializableExtra("device");
onConnectDevice(model.getDevice());
}
};