Azure push notifications not received when android app is closed
<p>For quick information, I am using the following tutorial:</p>

<p><a href="https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-android-push-notification-google-gcm-get-started/" rel="nofollow noreferrer">https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-android-push-notification-google-gcm-get-started/</a></p>

<p><strong>Problem</strong> I can receive the push notifications (sent from my Nodejs server) when application is opened. However, when I close the application and remove it from recents too, then I don't receive any push notifications. I am using Azure Push Notifications Hub.</p>

<p>All the code is in above link, however, I am also putting it here as how I have implemented it.</p>

<p>Added the following chunks in Android Manifest file : ( tag not shown for simplicity, I have added chunks in correct places)</p>

<pre><code>&lt;meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" /&gt;

&lt;service android:name="&lt;your package&gt;.MyInstanceIDService" android:exported="false"&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="com.google.android.gms.iid.InstanceID"/&gt;
    &lt;/intent-filter&gt;
&lt;/service&gt;

&lt;service
    android:name="&lt;your package&gt;.RegistrationIntentService"
    android:exported="false"&gt;
&lt;/service&gt;

&lt;receiver android:name="com.microsoft.windowsazure.notifications.NotificationsBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND"&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt;
        &lt;category android:name="&lt;your package name&gt;" /&gt;
    &lt;/intent-filter&gt;
&lt;/receiver&gt;

&lt;uses-permission android:name="android.permission.INTERNET"/&gt;
&lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt;
&lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt;
&lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /&gt;

&lt;permission android:name="&lt;your package&gt;.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt;
&lt;uses-permission android:name="&lt;your package&gt;.permission.C2D_MESSAGE"/&gt;
</code></pre>

<p>The following are the classes that I added according to tutorial:</p>

<pre><code>public class NotificationSettings {
    public static String SenderId = "&lt;Your project number&gt;";
    public static String HubName = "&lt;Your HubName&gt;";
    public static String HubListenConnectionString = "&lt;Your default listen connection string&gt;";
}
</code></pre>

<p>The InstanceID listener service:</p>

<pre><code>import android.content.Intent;
import android.util.Log;
import com.google.android.gms.iid.InstanceIDListenerService;

public class MyInstanceIDService extends InstanceIDListenerService {

    private static final String TAG = "MyInstanceIDService";

    @Override
    public void onTokenRefresh() {

        Log.i(TAG, "Refreshing GCM Registration Token");

        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }
};
</code></pre>

<p>RegistrationIntentService Class:</p>

<pre><code>import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.microsoft.windowsazure.messaging.NotificationHub;

public class RegistrationIntentService extends IntentService {

    private static final String TAG = "RegIntentService";

    private NotificationHub hub;

    public RegistrationIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(Intent intent) {      
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String resultString = null;
        String regID = null;

        try {
            InstanceID instanceID = InstanceID.getInstance(this);
            String token = instanceID.getToken(NotificationSettings.SenderId,
                    GoogleCloudMessaging.INSTANCE_ID_SCOPE);        
            Log.i(TAG, "Got GCM Registration Token: " + token);

            // Storing the registration id that indicates whether the generated token has been
            // sent to your server. If it is not stored, send the token to your server,
            // otherwise your server should have already received the token.
            if ((regID=sharedPreferences.getString("registrationID", null)) == null) {      
                NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
                        NotificationSettings.HubListenConnectionString, this);
                Log.i(TAG, "Attempting to register with NH using token : " + token);

                regID = hub.register(token).getRegistrationId();

                // If you want to use tags...
                // Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/
                // regID = hub.register(token, "tag1", "tag2").getRegistrationId();

                resultString = "Registered Successfully - RegId : " + regID;
                Log.i(TAG, resultString);       
                sharedPreferences.edit().putString("registrationID", regID ).apply();
            } else {
                resultString = "Previously Registered Successfully - RegId : " + regID;
            }
        } catch (Exception e) {
            Log.e(TAG, resultString="Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
        }

        // Notify UI that registration has completed.
        if (MainActivity.isVisible) {
            MainActivity.mainActivity.ToastNotify(resultString);
        }
    }
}
</code></pre>

<p>And Notification Handler:</p>

<pre><code>public class MyHandler extends NotificationsHandler {
    public static final int NOTIFICATION_ID = 1;
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context ctx;

    @Override
    public void onReceive(Context context, Bundle bundle) {
        ctx = context;
        String nhMessage = bundle.getString("message");
        sendNotification(nhMessage);
        if (MainActivity.isVisible) {
            MainActivity.mainActivity.ToastNotify(nhMessage);
        }
    }

    private void sendNotification(String msg) {

        Intent intent = new Intent(ctx, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        mNotificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0,
                intent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(ctx)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("Notification Hub Demo")
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setSound(defaultSoundUri)
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}
</code></pre>

<p>There are still some chunks of code that I haven't included here but they can be seen from above link.</p>

<p>Kindly, let me know if there is any special permission to listen to push notification when app is not running.</p>

<p><strong>EDIT</strong></p>

<p>I think if somehow we keep this function onReceive alive even when app is closed then we can acheive this. Still not sure how to do this.</p>