Using FirebaseAnalytics from inside a library - android

I want to use FirebaseAnalytics inside a library project on android. I want the events logged to be reported to my Firebase console and not to the console of the app developer. I do not own or control the implementation of the app that will use the library.
Is this possible in any way?
My approach:
I have read this and found out that it is possible to create a FirebaseApp using my credentials as follows:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("Your AppId") // Required for Analytics.
.setApiKey("You ApiKey") // Required for Auth.
.setDatabaseUrl("Your DB Url") // If you wanted to
.build();
FirebaseApp.initializeApp(context, options, "CompanyA");
Is there a way to use this FirebaseApp to log events as in FirebaseAnalytics?

Related

Can two different Firebase project be used in one Android app, specifically crashlytics, messaging and performance extensions

For a couple of reasons we had to use multiple Firebase projects in one app. At the moment we have implemented auth extension to user one Firebase project and via code initialisation and crashlytics, performance and messaging to use another via the config file. We would like to make crashlytics and performance extensions to use the project that the auth extension uses and messaging to use the same one that it uses now.
I went through some initialisation examples but could not find anything related to crashlytics or performance extensions.
This is how I initialise different project for auth extension.
// credentials for auth project on Firebase
final String authAppName = BuildConfig.AUTH_APP_NAME;
final String authAppApplicationId = BuildConfig.AUTH_APPLICATION_ID;
final String authAppApiKey = BuildConfig.AUTH_APPLICATION_KEY;
List<FirebaseApp> listOfActiveApps = FirebaseApp.getApps(context);
if (!listOfActiveApps.isEmpty()) {
for (FirebaseApp app : listOfActiveApps) {
if (authAppApiKey.equals(app.getOptions().getApiKey())) {
return app;
}
}
}
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId(authAppApplicationId)
.setApiKey(authAppApiKey)
.build();
return FirebaseApp.initializeApp(context, options, authAppName);
Fabric/Firebaser here, great question - this behavior is generally not supported today, due to the way Crashlytics and Performance need to initialize, particularly when mixed with Auth.

Android - setup multiple Firebase projects with different services within one application

How do I integrate two Firebase projects within one Android app, so that both will still work independently?
The background:
Within my company's app I was using until now some old Firebase project mainly for GCM purposes. Now the decision within my organization has changed and we decided to move most of the services to the new Firebase project, with higher pricing plan - unfortunately the upgrade wasn't an option.
At this very moment I have:
a legacy project for Cloud Messaging stuff related to some marketing service,
a new Firebase project that will be used for Crashlytics, Remote Config flags and some more.
We don't want to move with Cloud Messaging due to the restrictions the switch causes - all the users would need to register to new notifications channel again. For Marketing reasons that's something unacceptable.
For now I was trying to use the new project's JSON configuration file initialized automagically by Gradle plugin and manual approach to register to the legacy FCM service like this:
FirebaseOptions fo = new FirebaseOptions.Builder()
.setApplicationId(appId)
.setApiKey(apiKey)
.setGcmSenderId(legacySenderId)
.build();
FirebaseApp firebaseApp = FirebaseApp.initializeApp(context, fo, "legacy");
HandlerThread thread = new HandlerThread("getLegacyTokenThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(() -> {
try {
String token = FirebaseInstanceId.getInstance(firebaseApp).getToken(legacySenderId, "FCM");
L.w("Received token: " + token);
} catch (IOException e) {
e.printStackTrace();
}
});
But this approach seems to be overriding my default project configuration, so the exceptions are not reported to Crashlytics belonging to the new project.
Can anyone suggest how do I make it to run both projects successfully?
Following #Frank's comment above, I didn't manage to make this kind of integration successful.
We ended up in creating a new app in the marketing service that is using new credentials instead of changing the previous ones, what would result in invalidation of the integration. This way we can target both old app's users who didn't update as well as the new ones.

Multiple public Firebase Database Instances in Android

I'm working on an assignment. I've to use Database provided by a provider 'hacker-news'. Also i've to use Firebase Authentication. I've setup a new project in my own account. Retrieving data from Hacker-news database works with below line. I'm able to fetch publicly accessible data with firebase child() APIs is
database = FirebaseDatabase.getInstance("https://hacker-news.firebaseio.com/");
But when i implemented Firebase Authentication and once user logs in it is giving error
Provided authentication credentials are invalid. This usually indicates your FirebaseApp instance was not initialized correctly. Make sure your google-services.json file has the correct firebase_url and api_key
I've spent lot of time on internet and found a link to implement multiple databases in single project -
Working with multiple Firebase projects in an Android app by Google
This works only if you are the owner of those Databases. Is there anyway i can access Hacker-news Database using SDK not REST-API?
FirebaseOptions options = new FirebaseOptions.Builder()
.setDatabaseUrl(getResources().getString(R.string.dbURL))
.setApiKey(getResources().getString(R.string.api))
.setApplicationId(getResources().getString(R.string.appID))
.setProjectId(getResources().getString(R.string.projectId))
.setStorageBucket(getResources().getString(R.string.storageBucket)).build();
//set all variable above as your need
boolean hasBeenInitialized=false;
List<FirebaseApp> fireBaseApps = FirebaseApp.getApps(getApplicationContext());
for(FirebaseApp app : fireBaseApps){
if(app.getName().equals("any_name")){
hasBeenInitialized=true;
}
}
if (!hasBeenInitialized) {
smaTeacher = FirebaseApp.initializeApp(this, options, "any_name");
}
database=FirebaseDatabase.getInstance(FirebaseApp.getInstance("any_name"));

how use firebase android for multiple id application

I have an application that is different for each user, id application is different for each user, so idApplication is dynamic. My problem is that json retrieved from firebase is linked to a single application id. How can I use one file json for all the applications I generate dynamically?
_______édit ____
I don't know thé application id, this application id is modified on a filé jenkins.properties on my project Android, and when jenkins générate New apk it do it with thé New id
Instead of relying on google-services.json and associated gradle plugin you can dynamically create FirebaseApp using something like following (I have this in dagger module)
FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
.setApiKey(apiKey)
.setApplicationId(someApplicationId)
.setDatabaseUrl(databaseUrl)
.setStorageBucket(storageBucket)
.build();
firebaseApp = FirebaseApp.initializeApp(context, firebaseOptions, "MyApp");

How to integrate firebase authentication with google app engine endpoints

I am writing a backend server for mobile applications.
The backend is running on google app engine and written in Java.
I want users to be able to login with federated identity such as facebook.
I saw that google supports this kind of authentication for mobile apps via firebase authentication. What would be the best way to integrate firebase authentication with my current app engine endpoints?
I already use the cloud platform's datastore and don't wish to work with the firebase database, only use the authentication method.
Thanks.
I'm also looking for an answer to this. My best 5c so far is to
Use FireBase to set up sign in methods etc. from the console
Use FireBase UI (in beta) for web or "Federated identity provider integration" for iOS/Android to set up the authentication flow
Retrive token/authentication details on your web/iOS/Android client and pass it on to your Cloud Endpoints as e.g., HTTP Request Headers
Inject the javax.servlet.http.HttpServletRequest to your endpoint methods (just add an argument and Google with inject the request object automatically)
Create a method that your Endpoint will call for each request (that needs authentication) that will handle the validation of the credentials you have passed on as HTTP Request Headers
Use FireBase Java SDK to call FireBase to validate the credentials (in order to do this, you need to export the json configuration from the Firebase console) and load the SDK with them, e.g., in one of your servlets:
#Override
public void init(ServletConfig config) {
try{
InputStream in = config.getServletContext().getResourceAsStream("/WEB-INF/firebase-privatekey.json");
FirebaseOptions options = new FirebaseOptions.Builder()
.setServiceAccount(in)
.setDatabaseUrl("YOUR_DATABASE_URL")
.build();
FirebaseApp.initializeApp(options);
log.info("Authentication enabled");
}
catch(Throwable t) {
t.printStackTrace();
log.warning("AUTHENTICATION DISABLED. Only public resources will be available");
}
}
You should be able to use Google Cloud Endpoints as an authentication proxy in front of your app. Endpoints supports validating Firebase Authentication tokens by configuring your OpenAPI template:
# Configure Firebase as an AuthN provider
securityDefinitions:
firebase:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
# Replace YOUR-PROJECT-ID with your project ID in the issuer and audiences fields
x-google-issuer: "https://securetoken.google.com/YOUR-PROJECT-ID"
x-google-audiences: "YOUR-PROJECT-ID"
x-google-jwks_uri: "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken#system.gserviceaccount.com"
# Add Firebase as an authN provider to specific endpoints...
security:
- firebase: []
Alternatively, you can use the Firebase Admin SDK to write authentication middleware that validates your tokens:
FirebaseAuth.getInstance().verifyIdToken(idToken)
.addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
#Override
public void onSuccess(FirebaseToken decodedToken) {
String uid = decodedToken.getUid();
// ...
}
});

Categories

Resources