我正在尝试将令牌存储在云数据库中。我稍后将在云函数中使用此令牌,以便向已添加为好友的用户发送通知。
但是,推送设备令牌不起作用,因为用户未经授权。他们获得授权后我无法保存它,因为令牌是在安装应用程序时生成的。
private static final String TAG = "FirebaseIDService";
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
/**
* 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) {
// Add custom implementation, as needed.
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference deviceToken = mFirebaseDatabase.getReference("device_token");
deviceToken.push().setValue(token).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Log.i("token push","Success!");
} else {
Log.i("token push","Failed !");
}
});
}
将令牌保存在共享首选项中,成功登录后将令牌保存到 Firebase 数据库,请记住,如果您移除应用缓存或重新安装应用,令牌始终不同