首页 文章

通过Firebase从Android调用 Cloud 功能

提问于
浏览
10

情况

我已经通过 functions.https.onRequest 创建了一个Google Cloud功能,当我将其在浏览器中粘贴并与我的Firebase设置完美集成时,该功能运行良好 . 这个函数有点像从后端公开的API方法,我想从客户端调用它 . 在此特定实例中,客户端是Android应用程序 .

问题

有什么方法可以通过Firebase调用Cloud Function来执行HTTP请求吗?或者我还需要执行手动HTTP请求吗?

4 回答

  • 0

    从版本12.0.0开始,您可以更简单的方式调用 Cloud 功能

    build.gradle 中添加以下行

    implementation 'com.google.firebase:firebase-functions:15.0.0'
    

    并使用以下代码

    FirebaseFunctions.getInstance()
        .getHttpsCallable("myCoolFunction")
        .call(optionalObject)
        .addOnFailureListener {
            Log.wtf("FF", it) 
        }
        .addOnSuccessListener {
            toast(it.data.toString())
        }
    

    您可以安全地在主线程上使用它 . 回调也在主线程上触发 .

  • 10

    这里有一个firebaser

    更新: is 现在是一个客户端SDK,允许您直接从支持的设备调用 Cloud 功能 . 有关示例和最新更新,请参阅Dima的答案 .

    原答案如下......


    @ looptheloop88是正确的 . 没有用于从Android应用调用Google Cloud Functions的SDK . 我肯定会file a feature request .

    但目前这意味着您应该使用从Android调用HTTP endpoints 的常规方法:

  • 6

    现在不可能,但正如另一个答案中所提到的,你可以从Android获得trigger functions using an HTTP request . 如果你这样做,那么's important that you protect your functions with an authentication mechanism. Here'是一个基本的例子:

    'use strict';
    
    var functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);
    
    exports.helloWorld = functions.https.onRequest((request, response) => {
      console.log('helloWorld called');
      if (!request.headers.authorization) {
          console.error('No Firebase ID token was passed');
          response.status(403).send('Unauthorized');
          return;
      }
      admin.auth().verifyIdToken(request.headers.authorization).then(decodedIdToken => {
        console.log('ID Token correctly decoded', decodedIdToken);
        request.user = decodedIdToken;
        response.send(request.body.name +', Hello from Firebase!');
      }).catch(error => {
        console.error('Error while verifying Firebase ID token:', error);
        response.status(403).send('Unauthorized');
      });
    });
    

    要在Android中获取令牌,您应该使用this然后将其添加到您的请求中,如下所示:

    connection = (HttpsURLConnection) url.openConnection();
    ...
    connection.setRequestProperty("Authorization", token);
    
  • 10

    是的,有可能:

    将此添加到app / build.gradle文件:

    实施'com.google.firebase:firebase-functions:16.1.0'


    初始化客户端SDK

    私人FirebaseFunctions mFunctions;

    mFunctions = FirebaseFunctions.getInstance();


    调用该函数

    private Task<String> addMessage(String text) {
    
    Map<String, Object> data = new HashMap<>();
    data.put("text", text);
    data.put("push", true);
    
    return mFunctions
            .getHttpsCallable("addMessage")
            .call(data)
            .continueWith(new Continuation<HttpsCallableResult, String>() {
                @Override
                public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                    // This continuation runs on either success or failure, but if the task
                    // has failed then getResult() will throw an Exception which will be
                    // propagated down.
                    String result = (String) task.getResult().getData();
                    return result;
                }
            });
       }
    

    Ref : Calling Firebase cloud functions

相关问题