Search code examples
androidfirebasebroadcastreceiverfirebase-cloud-messaging

How to get FCM notification data when app is not in task or killed?


I need to get data from FCM notifications in android and store them locally, but the problem is I am only able to do that when app is in foreground and then onMessageRecieved is called or when user taps on notification. I want to get notification's data when user gets notification and app is not running, not even in background or foreground. Please suggest something. Thank you in advance.


Solution

  • You can use BroadcastReceiver

    public class FirebaseDataReceiver extends BroadcastReceiver {
    
        private final String TAG = "FirebaseDataReceiver";
    
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Set<String> keys = intent.getExtras().keySet();
    
                for (String key : bundle.keySet()) {
                    Object value = bundle.get(key);
                    // You can use key and values here
                }
            }
        }
    }
    

    Manifest.xml

    <application>
    
        ............
    
        <receiver
            android:name="PackageName.FirebaseDataReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </receiver>
    
        ............
    
    </application>