22

Situation

I have created a Google Cloud Function through functions.https.onRequest, which is working nicely when I paste its URL in a browser and integrates well with my Firebase setup. This function is meant as somewhat of an API method exposed from the backend, which I'd like to invoke from clients. In this particular instance, the client is an Android app.

Question

Is there any way I can perform the HTTP request for the Cloud Function by invoking it through Firebase? Or will I have to still perform a manual HTTP request?

Community
  • 1
  • 1
tvkanters
  • 3,519
  • 4
  • 29
  • 45
  • what do you mean? Invoking the function using Firebase SDK? – looptheloop88 Mar 18 '17 at 11:51
  • 1
    For example, if I have an `https` function accessible at `https://.cloudfunctions.net/newSession`, I'd expect to be able to call something like `FirebaseFunctions.getInstance().get("newSession")`, similarly to how other Firebase functionality is accessed. – tvkanters Mar 18 '17 at 11:57
  • 3
    What I can suggest is to file a feature request for this functionality, because AFAIK there's no available standalone SDK for Firebase Functions yet. – looptheloop88 Mar 18 '17 at 12:03

4 Answers4

27

Since version 12.0.0 you can call cloud function in more simple way

Add following line in your build.gradle

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

And use following code

FirebaseFunctions.getInstance() // Optional region: .getInstance("europe-west1")
    .getHttpsCallable("myCoolFunction")
    .call(optionalObject)
    .addOnFailureListener {
        Log.wtf("FF", it) 
    }
    .addOnSuccessListener {
        toast(it.data.toString())
    }

You can use it on main thread safely. Callbacks is triggered on main thread as well.

You can read more in official docs: https://firebase.google.com/docs/functions/callable

Dmytro Rostopira
  • 10,588
  • 4
  • 64
  • 86
10

firebaser here

Update: There is now a client-side SDK that allows you to call Cloud Functions directly from supported devices. See Dima's answer for a sample and the latest updates.

Original answer below...


@looptheloop88 is correct. There is no SDK for calling Google Cloud Functions from your Android app. I would definitely file a feature request.

But at the moment that means you should use the regular means of calling HTTP end points from Android:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Can we call Google Cloud Functions from an Android app today? –  Jun 21 '17 at 07:46
  • @TheGameChanger Yes. If you have a problem, I recommend you create a new question with the [minimal code that reproduces that problem](http://stackoverflow.com/help/mcve). – Frank van Puffelen Jun 21 '17 at 14:38
  • Can you give me a link, please? –  Jun 21 '17 at 14:49
  • 1
    I don't have a problem. I just want to know how exactly are we supposed to call Google Cloud Functions from an Android app? I need a link, a name or a description? –  Jun 21 '17 at 19:18
6

It isn't possible for now but as mentioned in the other answer, you can trigger functions using an HTTP request from Android. If you do so, it's important that you protect your functions with an authentication mechanism. Here's a basic example:

'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');
  });
});

To get the token in Android you should use this and then add it to your request like this:

connection = (HttpsURLConnection) url.openConnection();
...
connection.setRequestProperty("Authorization", token);
Sir Codesalot
  • 7,045
  • 2
  • 50
  • 56
2

Yes it's possible :

  1. Add this to app/build.gradle file :

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


  1. Initialize the client SDK

    private FirebaseFunctions mFunctions;

    mFunctions = FirebaseFunctions.getInstance();


  1. Call the function

    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

Community
  • 1
  • 1