即使应用程序在后台,如何发送推送通知?我有一个Android应用程序,它从服务器接收推送通知,并且当应用程序在后台时它不会发送。仅在应用程序处于后台时发送。
答案 0 :(得分:0)
您需要在清单文件中添加它:
<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>
这是刷新令牌(实例服务)的类
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);
}
}
消息服务,您将在其中接收消息/通知
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
}
}
}
注意:不要忘记将google-service.json文件添加到项目的应用文件夹中