自从 Firebase 推出 Callable Functions 以来,您可以通过在 Firebase Cloud Functions 中创建一个可调用函数来轻松地在您的应用中使用它。
在您的index.js 中,创建一个函数并使其返回当前时间戳
exports.getTime = functions.https.onCall((data,context)=>{
return Date.now()
})
然后将其部署到 Firebase Cloud Functions
然后在您的 Android 应用中添加 Callable Functions 依赖项
implementation 'com.google.firebase:firebase-functions:16.1.0'
然后像这样从您的应用中调用该函数,并确保您键入的函数名称与您的云函数中的“getTime”相同
FirebaseFunctions.getInstance().getHttpsCallable("getTime")
.call().addOnSuccessListener(new OnSuccessListener<HttpsCallableResult>() {
@Override
public void onSuccess(HttpsCallableResult httpsCallableResult) {
long timestamp = (long) httpsCallableResult.getData();
}
});
如果你想在多个类中调用这个方法,你也可以做一个简单的接口
public interface OnGetServerTime {
void onSuccess(long timestamp);
void onFailed();
}
public void getServerTime(final OnGetServerTime onComplete) {
FirebaseFunctions.getInstance().getHttpsCallable("getTime")
.call()
.addOnCompleteListener(new OnCompleteListener<HttpsCallableResult>() {
@Override
public void onComplete(@NonNull Task<HttpsCallableResult> task) {
if (task.isSuccessful()) {
long timestamp = (long) task.getResult().getData();
if (onComplete != null) {
onComplete.onSuccess(timestamp);
}
} else {
onComplete.onFailed();
}
}
});
}