13

I can't seem to receive FCM Push Notifications that I send from the FCM console after app is killed on android, as in long-press the Overview button and swiping the app to be killed. It works absolutely fine when the app is running in the foreground or background. This may seem like a duplicate question but I have tried the other methods but I still cannot seem to get it.

NotificationService.java

public class NotificationService extends FirebaseMessagingService
{

private static final String TAG = "FCM Service";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    Log.d(TAG, "From: " + remoteMessage.getFrom());
    Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
    sendNotification(remoteMessage.getNotification().getBody());
}

private void sendNotification(String messageBody) {

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        android.support.v4.app.NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

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

        notificationManager.notify(0, notificationBuilder.build());
}
}

TokenRefresh.java

public class TokenRefresh extends FirebaseInstanceIdService {

private static final String TAG = "FirebaseIDService";

@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);

    // TODO: Implement this method to send any registration to your app's servers.
    sendRegistrationToServer(refreshedToken);
}

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.

}

}

MainActivity.java

public class MainActivity extends AppCompatActivity {

Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    FirebaseMessaging.getInstance().subscribeToTopic("global");

    String token = ("fcm"+ FirebaseInstanceId.getInstance().getToken());


}

}
AL.
  • 36,815
  • 10
  • 142
  • 281
Darsshan
  • 896
  • 1
  • 11
  • 22
  • See the first answer in the following link ;-) http://stackoverflow.com/questions/37711082/how-to-handle-notification-when-app-in-background-in-firebase Have fun – Pouya Amirahmadi Feb 27 '17 at 03:51
  • @AL. I tried sending data messages from POST but then when I sent it to my app, the app crashes. I can receive notifications without payload normally through POST, but not data messages, is there something wrong with my code or anything extra needed in the manifest to receive data messages? – Darsshan Feb 27 '17 at 04:53
  • Can you post the stacktrace? – AL. Feb 27 '17 at 06:45
  • I/System.out: FCM Token=================>fM46b47CX4Y:APA91bELK7Oejzf_C3IDd-xZrJcK930pg72AOJCK7OeR74zxjZZzKUcSmcn8X_KJLHglyp1VP5QVW33nbFjfczOSx5H2F-7vkpXWQ3W85I_CzQZYGTKOKC_IsVeM8EERaJxJpb4tKG6T W/dalvikvm: VFY: unable to resolve instance field 151 I/FA: Tag Manager is not found and thus will not be used W/dalvikvm: threadid=11: thread exiting with uncaught exception (group=0x415aac80) I/Process: Sending signal. PID: 28652 SIG: 9 Disconnected from the target VM, address: 'localhost:8608', transport: 'socket' – Darsshan Feb 27 '17 at 08:00

4 Answers4

26

I had exactly the same problem. Notifications showed just fine in foreground and background mode, but not when the app was killed. Eventually I found this: https://github.com/firebase/quickstart-android/issues/41#issuecomment-306066751

The problem is with the debugging mode in Android Studio. To correctly test your notifications do the following: Run your app via debug in Android Studio. Swipe it away to be killed. Restart the app via the launcher icon on your phone. Swipe it away again (so it gets killed).

Send your notification and now you will see it!

Hope this solved your problem.

iDoes
  • 491
  • 4
  • 10
  • How to execute some code after receiving the push notification. Like replying back to the server with some data after receiving the push notification on the killed ios app via FCM or APNS? – Shubham1164 Feb 11 '19 at 17:00
  • On this page you can read about receiving push messages (https://firebase.google.com/docs/cloud-messaging/android/receive). As is stated here, data messages are handled in onMessageReceived whether the app is in the foreground or background. If your app is killed and the user taps on the notification they are returned to the app. In the onResume of my MainActivity.java I checked if the intent had a 'url' (notificationUrl = getIntent().getStringExtra("url");) which was send with the notification. If so, I knew the activity was opened by clicking a notification and I would do something with it. – iDoes Feb 12 '19 at 09:55
  • I am unable to do it on IOS – Shubham1164 Feb 12 '19 at 10:09
  • Aahh I am sorry. I read your question wrong. I don't know how it works for iOS, only for Android. – iDoes Feb 12 '19 at 10:10
2

You need to mark your Firebase Service class to not get killed together with your main app.

    ComponentName componentName = new ComponentName(
            applicationContext,
            FCMService.class);

    applicationContext.getPackageManager().setComponentEnabledSetting(
            componentName,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);

And you can check this real implementation in Java

Rafael Setragni
  • 160
  • 1
  • 6
0

Try adding BroadcastReceiver to your MainActivity.java

BroadcastReceiver mRegistrationBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                // checking for type intent filter
                if (intent.getAction().equals(Config.REGISTRATION_COMPLETE)) {
                    // gcm successfully registered
                    // now subscribe to `global` topic to receive app wide notifications
                    FirebaseMessaging.getInstance().subscribeToTopic(Config.TOPIC_GLOBAL);

                    displayFirebaseRegId();

                } else if (intent.getAction().equals(Config.PUSH_NOTIFICATION)) {
                    // new push notification is received

                    String message = intent.getStringExtra("message");

                    Toast.makeText(getApplicationContext(), "Push notification: " + message, Toast.LENGTH_LONG).show();

                    txtMessage.setText(message);
                }
            }
        };

        displayFirebaseRegId();
    }

    // Fetches reg id from shared preferences
    // and displays on the screen
    private void displayFirebaseRegId() {
        SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
        String regId = pref.getString("regId", null);

        Log.e(TAG, "Firebase reg id: " + regId);

        if (!TextUtils.isEmpty(regId))
            txtRegId.setText("Firebase Reg Id: " + regId);
        else
            txtRegId.setText("Firebase Reg Id is not received yet!");
    }

    @Override
    protected void onResume() {
        super.onResume();

        // register GCM registration complete receiver
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.REGISTRATION_COMPLETE));

        // register new push message receiver
        // by doing this, the activity will be notified each time a new message arrives
        LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
                new IntentFilter(Config.PUSH_NOTIFICATION));

        // clear the notification area when the app is opened
        NotificationUtils.clearNotifications(getApplicationContext());
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
        super.onPause();
    }
}
-5

Try Change the Flag

 Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT);
Cecil Paul
  • 595
  • 6
  • 27
  • 3
    How could this help? These are notifications coming from an FCM server, not something your app is generating. There's no opportunity to create an intent. – James Moore Jul 31 '17 at 16:28