Push Notifications when app is closed

106,795

Solution 1

Yes, it is possible 'to receive notifications from google cloud message when the application is fully closed'.

Infact, A broadcast receiver is the mechanism GCM uses to deliver messages. You need to have implement a BroadcastReceiver and declare it in the AndroidManifest.xml.

Please refer to the following code snippet.

AndroidManifest.xml

<receiver
    android:name=".GcmBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
        <!-- Receives the actual messages. -->
        <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        <category android:name="com.google.android.gcm.demo.app" />
    </intent-filter>
</receiver>
<service android:name=".GcmIntentService" />

Java code

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Explicitly specify that GcmIntentService will handle the intent.
        ComponentName comp = new ComponentName(context.getPackageName(),
                GcmIntentService.class.getName());
        // Start the service, keeping the device awake while it is launching.
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }
}

When GCM delivers a message to your device, BroadcastReceiver will receive the message and call the onReceive() function, wherein you may start a service to actually perform the intended task for you.

The above Code example uses a specialized BroadcastReceiver called WakefulBroadcastReceiver, which makes sure that the device doesn't go to sleep, while the service is doing its work.

Refer to the Official Android Page for the same: https://developer.android.com/google/gcm/client.html

Solution 2

When the app is closed forcelly by the user : notifications don't arrive

It's a feature of the Android platform. Force stopping an application by the user puts the application in a stopped state and none of its code is run, including any broadcast receivers declared in manifest. Only when the user explicitly launches the app it is put in a state where the receivers get fired.

For further reading: http://www.doubleencore.com/2014/06/effects-android-application-termination/

Solution 3

After some testing I did on this issue, I found out that it behaves differently on how the app is closed. If you close the app while the cable is connected to the device, it then blocks every notification when the app is closed. However, if you take the cable off the device and close the app, when you send the notification, everything works again, as it should!

In case you get a "Waiting for the Debugger" popup message, just restart the device and then send a test notification!

Solution 4

It will not work on killing the app from task manager, but work if you just slide it away from recent. I tried doing on whatsapp by killing it and ask someone to send a msg to me, and I haven't got any notification. Then I started the app, and I got notification.

Solution 5

Firebase API has two types of messages, they call them:

  • notification
  • data

find more information from here

IMPORTANT : You can't send data payload messages from Firebase Console, Console only delivers notification message. So I have mentioned how to send push notification using postman please follow below steps for that.

You must send push messages with data payload because of data payload - Doesn't matter whether your application is in the foreground or background or killed, these messages will always be delivered to onMessageReceived() method.

In Android 8.0 Oreo if the application is closed, then notification is not received It is because of DOZE mode and battery optimization,you just have to turn off battery optimization for all apps or particular app.

Turn off battery optimization for your app by below step:

Settings>> Battery >> battery Optimization >> find your app >> select >> if optimized click on don't optimize >> try pushing notification

Send push notification using postman

Step 1: https://fcm.googleapis.com/fcm/send

Step 2: Set this two into Header

Authorization : key=AIzaSyBuRl1Ikz3VXFvU7xW9mmg51lJ3uDSH

Content-Type : application/json

Step 3: Send this json

{
 "to" : "eb9HgFulyzU:APA91bFMLReWWwilNFfJ1fnXZ0A2PhJAYsabg-UcK_dHgHQcstTzcxLs4_mqgOmZtUiyLMne4JaOG7f8KH7pWxB7JugOGCCYgjd4fUynRBKZvNUgjaj2UdJB2Ux8VocszuUydCX",
 "data" : {
     "message" : "First Notification",
     "title": "Push Notification",
     "key_1" : "Key 1 value",
     "key_2" : "Hello"
 }
}

Hope this helps..

Enjoy :) :)

Share:
106,795
Dani Andújar
Author by

Dani Andújar

Updated on June 23, 2020

Comments

  • Dani Andújar
    Dani Andújar about 4 years

    Do you know if is it possible to receive notifications from google cloud message when the application is fully closed?

    I know if it's open or in background yes, but can it be programmed any way in order to receive them?

    EDIT:

    I continue without receiving notifications when the app is closed.

    I attached the code in case I have an error and I am not watching it.

    MANIFEST

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.frab"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="com.frab.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <permission
    android:name="com.frab.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />
    
    <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
    
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
    android:name="com.frab.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    
    <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    </activity>
    
    <receiver
    android:name=".GGMBroadcastReceiver"
    android:permission="com.google.android.c2dm.permission.SEND" >
    <intent-filter>
    <action android:name="com.google.android.c2dm.intent.RECEIVE" />
    <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
    <category android:name="com.something" />
    </intent-filter>
    </receiver>
    
    <service android:name=".GCMIntentService" />
    </application>
    
    </manifest>
    

    BROADCAST RECEIVER

    package com.something;
    
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    
    import com.activities.SignIn;
    import com.google.android.gcm.GCMBaseIntentService;
    import com.objects.Globals;
    
    public class GCMIntentService extends GCMBaseIntentService {
    private static final String TAG = "GGM <-----> FRAB";
    private Bundle extras;
    
    public GCMIntentService() {
    super(Globals.SENDER_ID);
    }
    
    @Override
    public void onDestroy() {
    Log.d(TAG, "terminando servicio");
    }
    
    @Override
    protected void onRegistered(Context context, String registrationId) {
    Log.i(TAG, "onRegistered: registrationId=" + registrationId);
    }
    
    @Override
    protected void onUnregistered(Context context, String registrationId) {
    Log.i(TAG, "onUnregistered: registrationId = " + registrationId);
    }
    @Override
    protected void onMessage(Context context, Intent data) {
    extras = data.getExtras();
    String message = extras.getString("msg");
    Log.d("******", message);
    sendNotification(message);
    }
    
    @Override
    protected void onError(Context arg0, String errorId) {
    Log.e(TAG, "onError: errorId = " + errorId);
    }    
    }
    
    package com.something;
    
    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.support.v4.content.WakefulBroadcastReceiver;
    
    public class GGMBroadcastReceiver extends WakefulBroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(), GCMIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
    }
    }
    

    When the app is open : OK

    When the app is in background : Ok

    When the app is closed forcefully by the user : notifications don't arrive

    What is the problem?

    Thank you very much.

  • Nitesh Kumar
    Nitesh Kumar over 8 years
    I don't receive notification even if I slide it away from recent apps on some devices like Xiaomi. There is an "Autostart" feature in these phones and if I enable autostart for my app then I receive push notification even if I slide the app away from recent apps. But I don't want the user to manually enable the autostart for my app. There are other apps like whatsapp, facebook who have autostart enabled already. How should I do enable the autostart automatically when the app installs?
  • berserk
    berserk over 8 years
    @NiteshKhatri Sorry, no clue about autostart.
  • Giru Bhai
    Giru Bhai over 8 years
    Is there any method to notify users such that you cannot receive notification until app open,since for e.g. autostart manager disable app on install. So GCM Push not working.
  • shijin
    shijin about 8 years
    Its ok..if the notification don't arrive when app is closed. But when the app is launched again I didn't get those notification. Is it permanently lost?
  • Rana
    Rana about 8 years
    @yuen shi: yes . When your app is closed still GCM push message deliver to your device. becouse of force closed app you don't get any notification.
  • Bala Saikrupa Puram
    Bala Saikrupa Puram about 8 years
    But it is not working in pre lollipop devices, it is working fine in lollipop devices.do i need to add any thing for pre lollipop devices.
  • Bala Saikrupa Puram
    Bala Saikrupa Puram about 8 years
    But it is not working in pre lollipop devices, it is working fine in lollipop devices.do i need to add any thing for pre lollipop devices?
  • Md. Sajedul Karim
    Md. Sajedul Karim over 7 years
    i am also fetching same issue in huawei phone. Actually, it didn't getting any notification when app is cleared from task list. Actually it kill the app when we do this. Have you find any solution?
  • Roon13
    Roon13 over 7 years
    Then how does it work for whatsapp app and other chat apps?
  • berserk
    berserk over 7 years
    @Md.SajedulKarim That doesn't seem like normal behavior. Clearing app from recent should not kill app (tho any app can be killed by OS in case of low memory, but I don't think it will happen as soon as you slide it away). I will say there is something wrong with the device OS (maybe vendor's fault)
  • Dhananjay M
    Dhananjay M over 7 years
    I ain't sure, but Whatsapp and other apps must have maintained some status(like sent, delivered, read) of the messages received by the app user. They would set the status accordingly. Suppose if a message was sent to the device the status of that message would be "sent". If the message was not yet delivered to the application due to some reason, then status would remain "sent". Now the server identifies this status and sends again this message. When delivered to the app, they would set it's status as "delivered".
  • Rahul Hawge
    Rahul Hawge over 7 years
    Its not working for lenovo devices.. for other devices it works fine
  • MatPag
    MatPag about 7 years
    WhatsApp and similar probably use the SyncAdapter registered in the Accounts panel to perform some task when the app is force closed.
  • Sumit Kumar
    Sumit Kumar almost 7 years
    It is also not working with MI phones,version android 6. Have any solution
  • Sahil Bajaj
    Sahil Bajaj almost 7 years
    For some phones, forcing a service to run in the background helps. Use AlarmManager to schedule a service when the app exits. This should make sure that the App process is alive and receivers listening to the broadcasts.
  • Deepak
    Deepak over 6 years
    Hi, I am adding alarm manager in main activity. It work's fine in mi and Samsung devices but in VIVO and OPPO phones I don't get any notifications.
  • JSN
    JSN over 6 years
    How can I do it on ionic 2?
  • Mik
    Mik over 5 years
    I'm going to give more details on this: If you're debugging the app, the notifications will work at first. Then if you close the app (swipe from recent), they won't work. You must then re-launch the app once manually from the device (not by debugging). You can close it then and notification will arrive. It looks like when you close a debugging app, all of its services are stopped. I lost 2 days because of this.
  • Mik
    Mik over 5 years
    That is not correct. The services for notifications etc continue to run after the app has been closed.
  • user1034912
    user1034912 almost 3 years
    So bascially, we need to send 'Data' payload for the messaging to work. Why the hell doesn anyone want 'Notification' payload then? Its utter useless if app must be opened to receive notifications