Search code examples
androidandroid-listviewbroadcastreceivergoogle-cloud-messaging

Android How to update my messages list while activity is in background?


I have a simple chat application and i'm using GCM to receive the messages and update de UI, the thing is that when the app goes to background the UI is not being updated, how can i update the UI while the app is in background?

This is the code:

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
            String iDuser = intent.getExtras().getString(EXTRA_IDQUIEN);
            String fEcha = intent.getExtras().getString(EXTRA_FECHA);
            String audio = intent.getExtras().getString(EXTRA_AUDIO);
            String video = intent.getExtras().getString(EXTRA_VIDEO);
            String imagen = intent.getExtras().getString(EXTRA_IMAGEN);
            Log.e("fecha", " "+fEcha);
            if (iDuser.equals(iduser)) {
                WakeLocker.acquire(getApplicationContext());
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("mensaje", newMessage);
                map.put("fecMens", fEcha);
                map.put("audio", audio);
                map.put("imagen", imagen);
                map.put("video", video);
                map.put("idusuario", iDuser);
                arraylist.add(map);
                Log.e("añadiendo el mensaje", newMessage);
                adapter.notifyDataSetChanged();
                WakeLocker.release();
            }
        }
    };

On first run of activity i do an asynctask to download the messages timeline, then while the activity is visible i get updated the UI using the broadcast receiver.

Now i need to update that UI while the app goes to background, like whatsapp do.

Appreciate any help


Solution

  • Is there a reason you can't do these UI updates in onResume()? That would be the preferred method, since you don't really want your app to be doing lots of UI work while it's not visible anyway.

    You could have a private boolean needsUiUpdate = false; in your Activity class. Then, in your onReceive() you can set needsUiUpdate = true;. And finally, in your Activity's onResume(), you have something like this:

    @Override
    public void onResume() {
        if (needsUiUpdate) {
            doUiUpdates();
        }
    }