我使用 FCM 向客户端 (android( 发送消息,
但我会有很多客户端 android,我只想向一台设备发送消息,而不是向所有人发送消息。我该怎么做?现在,当我发送消息时,我发送给所有人
如果您有所有用户的"FCM 注册令牌",则可以使用该用户的 FCM 注册令牌向单个设备或用户发送消息
向一台设备发送消息,而不是向每台设备发送消息
从客户端应用注册 FCM 时,你将收到该设备的令牌。您可以将其传递到服务器并将其保存在那里。稍后,您可以使用该特定设备令牌向该设备发送 FCM 消息。
返回 FCM 令牌的代码片段如下所示
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
private static final String TAG = "MyFirebaseIIDService";
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is called when the InstanceID token
* is initially generated so this is where you would retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
/**
* 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) {
// TODO: Implement this method to send token to your app server.
}
}
查看官方文档