How do I send a push a notification, even when the app is in the background? I have an android app that recieves push notifications from a server and it does not send when the app is in the background. it only sends when the app is in the background.
You need to add this in your manifest file:
<service
android:name=".name_of_your_firebase_instace_service"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".nname_of_your_firebase_messaging_service
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
This is the class for refreshing token(instance service)
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
@Override
public void onTokenRefresh() {
super.onTokenRefresh();
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// sending reg id to your server
sendRegistrationToServer(refreshedToken);
Log.d("NewToken",refreshedToken);
}
private void sendRegistrationToServer(final String token) {
// sending gcm token to server
Log.e(TAG, "sendRegistrationToServer: " + token);
}
}
Mmessage service where you will receive your message/notification
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getSimpleName();
private NotificationUtils notificationUtils;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage == null)
return;
// Check if message contains a notification payload.
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());
//you can send your own custom notification here if you are sending notification in data tag or if you are sending notification with "notification tag" it will handle it automatically
}
}
}
Note: do not forget to add your google-service.json file in app folder of your project
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.