Firebase Lecture PDF
Document Details
Uploaded by WellMadeDramaticIrony2051
Tags
Summary
Firebase is a platform for building mobile and web applications. It includes various tools and features for building user-friendly apps. It supports multiple platforms and languages. The document also discusses the build and run categories within firebase products.
Full Transcript
12/28/2024 Firebase 1 What is Firebase Firebase is Google's client-side app development platform based on google could and integrates with most of google tools as well, like ads. Its multiplatform client for iOS, Android, Flutter,...
12/28/2024 Firebase 1 What is Firebase Firebase is Google's client-side app development platform based on google could and integrates with most of google tools as well, like ads. Its multiplatform client for iOS, Android, Flutter, and web (like Angular, React, and Vue) uses Javascript and Typescript, Java, Kotlin, Swift, Objective-C, and C++. It's a collection of almost 20 products that help you build the product Google architecture. They break this product into build and run categories. 2 1 12/28/2024 Firebase as a Client-Side Development Platform Google Cloud Integration: Built on Google's robust cloud infrastructure, Firebase ensures scalability, reliability, and high availability. Compatibility with Google Tools: Works seamlessly with Google Ads, Google Analytics, and other Google products to provide a holistic development experience. Multi-platform Support: iOS Android Web frameworks (Angular, React, Vue, etc.) Flutter (Google's UI toolkit) Programming languages such as JavaScript, TypeScript, Java, Kotlin, Swift, Objective-C, and C++. 3 Why is this important? Firebase's cross-platform capabilities allow developers to write once and deploy across multiple platforms, reducing development time and effort. Firebase supports development across: Mobile: Android and iOS apps, including integration with platform-specific tools like Android Studio and Xcode. Web Applications: Full support for modern frameworks like Angular, React, and Vue.js. Cross-Platform Frameworks: Flutter (Google’s UI toolkit for creating native apps). Unity for game development. C++ for native performance-driven applications. 4 2 12/28/2024 Firebase Build Category: Managed Infrastructure: App Check: Protects backend resources by verifying that incoming traffic originates from your app. Supports Android, iOS, and Web. Prevents abuse and ensures only legitimate users access your backend. Hosting: Provides secure, global hosting for static and dynamic web apps. Key Features: Supports modern frameworks like Angular, React, and Vue.js. Deploys directly from GitHub with continuous integration support. Global content delivery network (CDN) for fast loading. 5 Firebase Build Category: Authentication: Simplifies user login and onboarding with pre-built UI and secure authentication methods. Supported Methods: Email and Password. Social providers: Google, Facebook, Twitter, GitHub. Phone number authentication. Features: Secure token-based authentication. Provides user management APIs to handle sign-in and sign-out. 6 3 12/28/2024 Firebase Build Category: Firestore vs. Realtime Database: Firestore (NoSQL): Flexible, scalable, and cloud-hosted database. Real-time updates and offline support. Structured data with documents and collections. Advanced querying capabilities. Realtime Database: Original Firebase database solution. Simple, JSON tree-based structure. Real-time synchronization across devices. Best for simpler use cases or when latency is critical. 7 Firebase Build Category: Cloud Storage for Firebase: Provides robust and secure file storage. Automatically synchronizes files between the app and the cloud. Key Features: Stores user-generated content like photos, videos, and documents. Ensures seamless integration with Firebase Authentication. Flexible rules for managing read/write permissions. 8 4 12/28/2024 Firebase Build Category: Extensions: Pre-packaged, open-source solutions for common development challenges. Popular Extensions: Trigger Email: Automatically send emails based on events like user sign-ups. Resize Images: Dynamically resize uploaded images for better performance. Translate Text: Use Google Translate to localize app content. Benefits: Saves development time by automating repetitive tasks. Reduces errors by using tested solutions. Easy to integrate and configure within the Firebase Console. 9 Firebase Run Category: A/B Testing: A method of comparing two or more app variations to determine which performs better. Key Features: Experiment with UI changes, new features, and app performance. Roll out updates to a subset of users to evaluate impact before full deployment. How it Works: Create experiments in the Firebase Console. Define goals such as increased user engagement, conversion rates, or retention. Analyze results using integrated Google Analytics. 10 5 12/28/2024 Firebase Run Category: Crashlytics: A real-time crash reporting tool to help identify and fix stability issues in your app. Key Features: Provides detailed crash reports with contextual information. Alerts for new and trending issues. Integration with Slack and other tools for instant notifications. How it Works: Integrate Crashlytics SDK into your app. Monitor crashes and user-impacting issues via the Firebase Console. 11 Firebase Run Category: Google Analytics: A free tool to measure app usage, user behavior, and engagement. Key Features: Tracks metrics like active users, session duration, and retention. Provides user demographics and behavior insights. Enables event tracking for custom user interactions. How it Works: Integrate Firebase Analytics SDK into your app. Define events and parameters to track specific user actions. View detailed reports in the Firebase Console. 12 6 12/28/2024 Firebase Run Category: Cloud Messaging: Definition: A service to send targeted push notifications to engage users. Key Features: Send notifications to specific user segments or all users. Supports scheduling and automation. Free to use with unlimited messages. How it Works: Configure Firebase Cloud Messaging (FCM) in the Firebase Console. Use FCM tokens to target specific devices. 13 Firebase Run Category: In-App Messaging: Definition: A tool to display contextual messages within the app. Key Features: Engage active users with real-time prompts. Customize messages based on user actions or app state. 14 7 12/28/2024 Firebase Run Category: Remote Config : A service that allows developers to update app features and settings without deploying a new version. Key Features: Customize app experience for different user segments. Roll out changes gradually and revert if needed. Use analytics data to define conditions for configuration. How it Works: Set default parameters in the app. Define dynamic parameters in the Firebase Console. Fetch and activate configurations in the app at runtime. 15 Firebase Run Category vs Firebase build Category: 16 8 12/28/2024 Firebase Console Google has several "consoles". These are webpages to control varying things. Other Examples: https://console.cloud.google.com/ google cloud console https://console.developers.google.com/apis/ for apis like maps https://developers.google.com/beacons/dashboard/ for beacons Firebase has its own as well. https://console.firebase.google.com/ 17 Analytics You need to only add firebase to the dependencies. The rest is done within the https://console.firebase.google.com/ You can look many different things, from first time usage, how long the app is up, demographics of users, etc. Data updates once every 24 hours. 18 9 12/28/2024 Cloud Messaging Basics, it's a push "notifications" system via google. Push, meaning the phone don't check for messages (ie pull messaging) and waste battery life and network bandwidth. Each device gets a unique Token. You can then have individual devices send messages to each other or group messages, or messages to all, based on the token. Requires a backend server to work. Either use googles hosting services or your own services. 19 Cloud Messaging Device Implements a firebaseMessaingService to receive the messages and decides what to do with them, in the app. Backend systems. Need to implement (like a ReST based system) to receive the messages the device is sending and forward them to the google site for distribution. Individual, group, or all. 20 10 12/28/2024 in-app messaging Not to be confused with cloud messaging, but the menu item is messaging. This allows you send a notification to the all (or some) of the devices where your app is instead. You need on include firebase message in dependencies (or bom) implementation ("com.google.firebase:firebase-inappmessaging") The rest is done in the console. 21 Notifications You create a message in the notifications section. Send the message. It will then show up on the device as a notification. If they click the notification and it will launch your app. Note, if the app is up then the users won't see it (without extra code from cloud messaging). You can code for in cloud messaging, so the message shows up as well. 22 11 12/28/2024 Authentication Allows the user to “log in" to your app. With any number of services using FirebaseUI Currently: phone number, email and password, google, Facebook, Twitter, and GitHub. Note Facebook and Twitter require their API key for it to work. You don't write the code; just call the method for sign-in or sign-out. It even keeps track of the password for emails. Dependencies, core plus implementation ("com.google.firebase:firebase-auth") implementation ("com.firebaseui:firebase-ui-auth:8.0.2") See https://github.com/firebase/FirebaseUI-Android 23 Setup and use private FirebaseAuth mFirebaseAuth; Private 24 12 12/28/2024 Setup and use private FirebaseAuth mFirebaseAuth; Private FirebaseAuth.AuthStateListener mAuthStateListener; 25 Setup and use private FirebaseAuth mFirebaseAuth; Private FirebaseAuth.AuthStateListener mAuthStateListener; mFirebaseAuth = FirebaseAuth.getInstance(); 26 13 12/28/2024 Example mFirebaseAuth.addAuthStateListener(mAuthStateListener); 27 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { 28 14 12/28/2024 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 29 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); 30 15 12/28/2024 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } 31 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { 32 16 12/28/2024 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { // User is signed out myActivityResultLauncher.launch(AuthUI.getInstance() 33 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { // User is signed out myActivityResultLauncher.launch(AuthUI.getInstance().createSignInIntentBuilder().setIsSmartLockEnabled(false) 34 17 12/28/2024 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { // User is signed out myActivityResultLauncher.launch(AuthUI.getInstance().createSignInIntentBuilder().setIsSmartLockEnabled(false).setAvailableProviders(Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build(), new AuthUI.IdpConfig.GoogleBuilder().build(), new AuthUI.IdpConfig.PhoneBuilder().build())) 35 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { // User is signed out myActivityResultLauncher.launch(AuthUI.getInstance().createSignInIntentBuilder().setIsSmartLockEnabled(false).setAvailableProviders(Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build(), new AuthUI.IdpConfig.GoogleBuilder().build(), new AuthUI.IdpConfig.PhoneBuilder().build())).build() ); 36 18 12/28/2024 mFirebaseAuth.addAuthStateListener(mAuthStateListener); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in use user.getDisplayName() to get the name. } else { // User is signed out myActivityResultLauncher.launch(AuthUI.getInstance() //see firebase UI for documentation..createSignInIntentBuilder().setIsSmartLockEnabled(false).setAvailableProviders(Arrays.asList( new AuthUI.IdpConfig.EmailBuilder().build(), new AuthUI.IdpConfig.GoogleBuilder().build(), new AuthUI.IdpConfig.PhoneBuilder().build())).build() ); } } }; mFirebaseAuth.removeAuthStateListener(mAuthStateListener); 37 Storage This allows for file storage in the cloud It handles all the networking and syncing between cloud and device. Again should use authentication. Can specify any of rules on what the users are allowed to write to/read from the storage. dependencies (using bom) implementation ("com.google.firebase:firebase-storage") 38 19 12/28/2024 Setup and use. private FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance(); 39 Setup and use. private FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance(); private StorageReference mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos"); Where chat_photos is directory in storage. 40 20 12/28/2024 Firebase Databases: Realtime and Cloud Firestore 41 Firebase Firestore (new database) Build responsive apps with a NoSQL document database that lets you structure data the way you like and retrieve it with expressive queries. Realtime Database (older Database) Store and sync data between your users in near-realtime, on or offline, with strong user-based security. We will need the console too: https://console.firebase.google.com/ 42 21 12/28/2024 Adding Firebase to your project In Studio (this is setup the Realtime Database) 43 Basic Setup In the browser Back in Studio 44 22 12/28/2024 Basic Setup You should now have the project in the firebase console as well 45 Through the console only Create a project and add the app project 46 23 12/28/2024 Including. In the build.gradle you can add each individual or add the BOM (Bill of Materials) and then which packages you need with the version numbers. Example: // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.3.1') // Declare the dependencies for the desired Firebase products without specifying versions implementation 'com.google.firebase:firebase-auth' implementation 'com.google.firebase:firebase-firestore' 47 RealTime database 48 24 12/28/2024 Realtime Database Is a cloud-based database with live connections to the app. The data is stored a json objects and is only intended for text, to allow for fast responses. Authentication is needed. Works even offline, with cached data then sync when online. dependencies implementation ("com.google.firebase:firebase-database:21.0.0") OR with the BOM included, just leave off the version number. 49 Database setup and use. Setup a connection and reference. FirebaseDatabase database = FirebaseDatabase.getInstance(); 50 25 12/28/2024 Database setup and use. Setup a connection and reference. FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference dbReference = database.getReference().child("messages"); 51 Database setup and use. Setup a connection and reference. FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference dbReference = database.getReference().child("messages"); To add a new value, use the push and setValue dbReference.push().setValue( friendlyMessage); Where friendlyMessage is a object holding the data. 52 26 12/28/2024 Cloud Firestore 53 FireStore Database. For flexibility, query the database, and scalable. Like realtime db, realtime updates and offline support. Uses a NoSQL data model. You have a collections, which contain documents, which can contain subcollections to build hierarchical data structures. Allows for efficient questions, by creating shallow queries or nested questions. https://firebase.google.com/docs/firestore/ 54 27 12/28/2024 Getting started. In the console turn on firestone. First add firestone to gradle (it's in the bom) implementation 'com.google.firebase:firebase-firestore' Access your database FirebaseFirestore db = FirebaseFirestore.getInstance(); Adding data, create a HashMap Map data = new HashMap(); data.put("back in 5 minutes", et_msg.getText().toString()); data.put("Arrow", "none"); 55 Adding data. Now Add the data to the level you want it. In this case, /sign/jim/ db.collection("sign").document("Jim").set(data) //hashmap previously created..addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Void aVoid) { Log.d(TAG, "DocumentSnapshot successfully written!"); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error writing document", e); } }); 56 28 12/28/2024 In the console it looks like this 57 Receive the data db.collection("users").document("Jim").get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { DocumentSnapshot snapshot = task.getResult(); Map data = snapshot.getData(); TestText = String.valueOf(data.get("text")); Arr = String.valueOf(data.get("Arrow")); } } }); 58 29 12/28/2024 To get multiple documents from a collection db.collection("users").get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { //iterate over the documents. for (QueryDocumentSnapshot document : task.getResult()) { //using document.getData() to get each one. } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } }); 59 Retrieve via a listener DocumentReference docRef = db.collection("sign").document("Jim"); docRef.addSnapshotListener(new EventListener() { @Override public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) { if (e != null) { Log.w(TAG, "Listen failed.", e); return; } //retrieve the data if it exists. if (snapshot != null && snapshot.exists()) { Map data = snapshot.getData(); TestText = String.valueOf(data.get("text")); Arr = String.valueOf(data.get("Arrow")); } } }); 60 30