androidgoogle-cloud-messagingpicassogcmlistenerservice

Download image in GcmListenerService and post notification


I am using a GcmReceiver with a listener that extends GcmListenerService. In my onMessageReceived method, I want to download a remote image (using Picasso lib) and once the image has been downloaded, post a notification to the user.

Code:

public class MainGcmListenerService extends GcmListenerService {
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String urlImage = data.getString("image_url");
        final Target target = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                  NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) ...... // build a notification with the downloaded image as a logo
                  NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                  mNotificationManager.notify(notificationType.getValue(), mBuilder.build());
            }
        };
        Handler uiHandler = new Handler(Looper.getMainLooper());
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                Picasso.with(context).load(urlImage)
                        .into(target);
            }
        });

This code works well most of the time, but sometimes the notification is not posted. I assume this is due to the fact that the GCM message thread gets killed before the download image task is finished. What would be a correct way to implement such a process in a GcmListenerService (downloading an image in onMessageReceived and then posting the notification once its finished)?


Solution

  • It's hard to provide a definite and complete answer. The way Picasso works, it may also depend on the internet connection of the receiving device, there still always a chance of the process being killed.

    What I would do in your situation though is to have a default image in the client app to be used for the Notification, if within a specific amount of time has already elapsed and the image still isn't downloaded completely, just to ensure that a Notification is shown.