- 在服务器端初始化您的 FCM
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
File configFile = new File("your-project-firebase-adminsdk-123magic-chars456.json");
String json = FileUtils.readFileToString(configFile, StandardCharsets.UTF_8.name());
InputStream in = new ByteArrayInputStream(json.getBytes());
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(GoogleCredentials.fromStream(in))
.build();
FirebaseApp.initializeApp(options);
- 要向特定用户发送 PUSH 通知,您需要知道他的注册令牌。
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
//.......
Message message = Message.builder()
.putData("userId", ""+yourUser.getId())
.putData("status", ""+yourUser.getStatus())
.putData("score", ""+yourUser.getScore())
.setToken(registrationToken)
.build();
String response = FirebaseMessaging.getInstance().send(message);
Log.info(this, "SendPush to: " + yourUser + ", response: " + response);
- 在安卓应用端。将此添加到 build.gradle(模块)
implementation platform('com.google.firebase:firebase-bom:29.0.0')
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-analytics'
这是你的 AndroidManifest.xml
<service
android:name="my.app.service.MyFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
- 现在在您的应用中实现 FirebaseMessagingService。它执行以下操作:
- 从您的服务器接收推送消息,
- 在设备上显示通知
- 从 FCM 获取registrationToken
- 将令牌发送到服务器(您可以将用户与其令牌绑定)
package my.app.service;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import com.google.firebase.FirebaseApp;
import com.google.firebase.iid.FirebaseInstanceIdReceiver;
import com.google.firebase.iid.internal.FirebaseInstanceIdInternal;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import androidx.core.app.NotificationCompat;
import my.app.R;
import my.app.MainActivity;
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onNewToken(String token) {
// Send token to server here!
}
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = handleNow(remoteMessage.getData());
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
MyLog.info(this, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
sendNotification(message);
}
/**
* Handle time allotted to BroadcastReceivers.
* @param data
*/
private String handleNow(Map<String, String> data) {
String userId = data.get("userId");
String status = data.get("status");
String score = data.get("score");
// Here you can process message data as you wish
String message = "Got data: userId=" + userId + ", status=" + status + ", score=" + score;
return message;
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
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 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_menu_camera)
.setContentTitle(getString(R.string.app_name))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}