Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android app is not receiving FCM notification when closed

I am checking Firebase Cloud Messaging to send notification. Have implemented it already and its receiving notification when app is in open state. But if I close app, its no longer gives notification. Is there any solution for this.

Code:

WebRequest wRequest;
wRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
wRequest.Method = "post";
wRequest.ContentType = " application/json;charset=UTF-8";
wRequest.Headers.Add(string.Format("Authorization: key={0}", AppId));

wRequest.Headers.Add(string.Format("Sender: id={0}", SenderId));

string postData = "{\"registration_ids\":[\"" + regIds + "\"], \"data\": "+ value +"}";

Byte[] bytes = Encoding.UTF8.GetBytes(postData);
wRequest.ContentLength = bytes.Length;

Stream stream = wRequest.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

WebResponse wResponse = wRequest.GetResponse();

Messaging service-

public class MessagingService extends FirebaseMessagingService {
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Map<String, String>  data = remoteMessage.getData();
        sendNotification(data);
    }

    public void showMessage(Map<String, String>  serverData) {
        Intent i = new Intent(this,MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,i,PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentIntent(pendingIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        manager.notify(Integer.parseInt(serverData.get("ItemId")),builder.build());
    }

    private void sendNotification(Map<String, String>  serverData) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0 /* request code */, intent,PendingIntent.FLAG_UPDATE_CURRENT);

        long[] pattern = {500,500,500,500,500};

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                .setContentTitle(serverData.get("Title"))
                .setContentText(serverData.get("Message"))
                .setAutoCancel(true)
                .setVibrate(pattern)
                .setLights(Color.BLUE,1,1)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(Integer.parseInt(serverData.get("ItemId")), notificationBuilder.build());
    }

}

Main activity-

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       FirebaseMessaging.getInstance().subscribeToTopic("test");
        FirebaseInstanceId.getInstance().getToken();
    }
}

Manifest-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="test.com.firebasenotify">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".MessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service android:name=".InstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

    </application>

</manifest>
like image 225
Anup Das Gupta Avatar asked Jun 16 '16 10:06

Anup Das Gupta


People also ask

Do push notifications work when app is closed?

Let's start with Android. The Android OS is designed to listen for push messages and upon receiving one, wake up the appropriate Android app to handle the push message, regardless of whether the app is closed or not.

How do I handle the Firebase notification when an app is in foreground?

Firebase notifications behave differently depending on the foreground/background state of the receiving app. If you want foregrounded apps to receive notification messages or data messages, you'll need to write code to handle the onMessageReceived callback.

Can I send push notifications without FCM?

Without FCM, you'd need to build more than three notification systems. You'd need one each for iOS and Android, but then you'd also need to accommodate all the different types of browsers for the web application to deliver push notifications without a hitch.


2 Answers

There's good solution and explanation about that issue here. You need to set high priority for notification to tell android react immediately, otherwise it takes couple of minutes to display received notification.

like image 132
slothdeboss Avatar answered Nov 15 '22 18:11

slothdeboss


There was no issue with the code. I was using Mi note 4, and somehow it does not show notification in Mi4 when app is closed. I tested with other android device and its working fine.

Thanks to Tim Castelijns and Frank van Puffelen for participating in the conversation.

like image 23
Anup Das Gupta Avatar answered Nov 15 '22 19:11

Anup Das Gupta