GCM Network Manager with notification display even if app is closed

406 Views Asked by At

I want to notify the user about the messages the she/he received while offline every time the the device is connected to the internet even if the app is closed. I found out that using GCM Network Manager is one way of solving the problem so I followed this tutorial on how to use GCM Network Manager, I added in its sample code a function to display a notification. This function is called everytime the broadcastreceiver is called.

Here is the code

.....
.......
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
    mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String taskId = intent.getStringExtra(CodelabUtil.TASK_ID);
            String status = intent.getStringExtra(CodelabUtil.TASK_STATUS);

            mTaskAdapter.updateTaskItemStatus(taskId, status);
            Notify("TEST", "TEST", context, intent);
        }
    };



private void Notify(String notificationTitle, String notificationMessage, Context ctx, Intent intent){
        Log.i("TEST", "Notify is called");
        NotificationManager manager;
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification myNotication;
        //Intent intent = new Intent("com.google.codelab.networkmanager");

        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1, intent, 0);

        Notification.Builder builder = new Notification.Builder(ctx);

        builder.setAutoCancel(false);
        builder.setContentTitle(notificationTitle);
        builder.setContentText(notificationMessage);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setContentIntent(pendingIntent);

//
        //builder.build();

        myNotication = builder.getNotification();
        manager.notify(11, myNotication);

    }

The problem is that the notification only displays when the app is in foreground but does not display whenever the app is closed.

Is there anything that I need to do?. Thank you. (Sorry for my bad english)

0

There are 0 best solutions below