Dialogs PDF
Document Details
Uploaded by FavoredMachuPicchu
Université d'Alexandrie
Tags
Summary
This document provides an overview of dialogs in Android development. It describes different types of dialogs and how to create them using the AlertDialog.Builder, along with examples of implementing different types of dialogs.
Full Transcript
12/1/2024 Dialogs 1 Dialog A dialog is a small window that prompts the user to provide additional information without taking up the entire screen. Such as : Prompt users for decisions (e.g., Save, Cancel, Exit). Display...
12/1/2024 Dialogs 1 Dialog A dialog is a small window that prompts the user to provide additional information without taking up the entire screen. Such as : Prompt users for decisions (e.g., Save, Cancel, Exit). Display additional information (e.g., Progress, Date/Time). 2 1 12/1/2024 Dialog Type AlertDialog: Standard dialog with up to three buttons (e.g., Positive, Negative, Cancel). ProgressDialog: Displays progress (deprecated for general use in newer APIs). DatePickerDialog and TimePickerDialog: Predefined dialogs for selecting dates or times. Custom Dialogs: User-defined layouts incorporated into a dialog. 3 Creating a Dialog Use the AlertDialog.Builder to create the dialog You can have up to three buttons, “positive”, “negative” and cancel To create the following Dialog Set the positive and negative, and disable cancel. 4 2 12/1/2024 Code: with two listeners, one for each button. AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Winner!").setCancelable(false).setPositiveButton("Next Level", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss();}.setNegativeButton("Quit", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); } builder.show(); 5 AlertDialog Instead of buttons, you can have it as radio buttons (and more then just three); Use Builder.setSignleChoiceItems Where we send a CharSequence[] of items. final String[] items = {"Remove Walls", "Add Walls", "Add/Remove Objects", "Add/Remove Score"}; 6 3 12/1/2024 final String[] items = {"Remove Walls", "Add Walls", "Add/Remove Objects", "Add/Remove Score"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Choose Type:"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); if (item == 0) {} Builder.show(); 7 DialogFragment Instead of using an the alertdialog builder, you can use dialogFragment. you implement onCreateDialog(Bundle) Instead of (or in addition to ) onCreateView DialogFragments can be added to a framelayout just like fragments OR we can use the show method All the demos are going to use show, instead putting in the framelayout, since you already saw how to do it. 8 4 12/1/2024 Why Use DialogFragments? Lifecycle-aware. Better alignment with fragments in modern Android. 9 DialogFragment To show the fragment, use the following as an example: FragmentManager fm = getSupportFragmentManager(); EditNameDialogFrag editNameDialog = new EditNameDialogFrag(); editNameDialog.show(fm, "fragment_edit_name"); Show function, causes the dialogFragment to popup on the screen. 10 5 12/1/2024 extends DialogFragment and usesAlertDialog @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = LayoutInflater.from(requireActivity()); FragmentEditNameBinding binding = FragmentEditNameBinding.inflate(inflater); AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(requireActivity(), R.style.ThemeOverlay_AppCompat_Dialog)); builder.setView(binding.getRoot()).setTitle("Hello"); builder.setPositiveButton("Done", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { mListener.onFinishEditDialog(binding.txtYourName.getText().toString()); dismiss(); } }).setCancelable(false); Dialog dialog = builder.create(); return dialog; 11 Input Keyboard, touch, controllers, and device sensors 12 6 12/1/2024 View For most input, you add a custom listener to a View class EditView has a keyboard listener, since it accepts input. You add a listener to a View (widgets) and then it only work for that widget You can’t have a listener for a “screen” Unless the view takes up the entire screen The exception is the Sensor, which is for the device. 13 View There is a View class that you can extend and use to create custom Views We’ll use an ImageView widget and add listeners 14 7 12/1/2024 A Note View will need several attributed in order to work with these listeners In the xml you will need to add android:focusable="true" android:focusableInTouchMode="true" android:clickable="true" 15 Keyboard input 16 8 12/1/2024 View.OnKeyListener For "keyboard" input Implement the View.OnKeyListener And override public boolean onKey(View v, int keyCode, KeyEvent event) Note, that there is not a char field here. You get the KeyCode as a parameter or event.getKeyCode() 17 View.OnKeyListener What key was pressed? Use event.getMatch(char[] chars) Pass it an array of characters you want to test against. If it matches, then returns that character Else returns ‘\0’ Use keycode == KeyEvent. Constants Example: KeyEvent.KEYCODE_0 for Zero Gives you access to any key that was pushed: KEYCODE_CAMERA, KEYCODE_DPAD_LEFT KEYCODE_ENDCALL, KEYCODE_VOLUME_DOWN, etc 18 9 12/1/2024 View.OnKeyListener Add the listener to the view ImageView in our case iv.setOnKeyListener(new myKeyListener()); When the ImageView has focus, then the keylistener will be called for any key events. 19 View Overrides When extending a View class you also can override several more You also override them in an activity as well. onKeyDown(int, KeyEvent) Called when a new key event occurs. onKeyUp(int, KeyEvent) Called when a key up event occurs. onTrackballEvent(MotionEvent) Called when a trackball motion event occurs. There is also a touchEvent 20 10 12/1/2024 Touch input 21 Touch Events. There is an OnTouchListener But you can also use the OnClickListener and OnLongClickListener as well. Normally associated with buttons. 22 11 12/1/2024 View.OnTouchListener Implement the View.OnTouchListener And override public boolean onTouch(View v, MotionEvent event) return true if event consumed, false otherwise. the event has all the information about the touch event. 23 View.OnTouchListener MotionEvent getX(), getY() returns the X, Y location of the touch in the Widget Not the position on the screen. getRawX(), getRawY() returns the original raw X and Y coordinate, which is the position on the screen. getAction() Return the kind of action being performed one of either ACTION_DOWN, ACTION_MOVE, ACTION_UP, or ACTION_CANCEL. 24 12 12/1/2024 View.OnTouchListener MotionEvent getX(), getY() returns the X, Y location of the touch in the Widget Not the position on the screen. getRawX(), getRawY() returns the original raw X and Y coordinate, which is the position on the screen. getAction() Return the kind of action being performed one of either ACTION_DOWN, ACTION_MOVE, ACTION_UP, or ACTION_CANCEL. 25 13 12/13/2024 Input Keyboard, touch, and device sensors 37 Defining Input Systems in Android Keyboard Input Typing in an EditText or triggering actions with the Enter key. Touch Input Swipes, long presses, and multi-touch are common Device Sensors Detecting phone orientation or steps in a fitness app. 38 1 12/13/2024 View It plays a central role in handling inputs by acting as the interaction layer between users and the app. Focus and Interaction: Each View can gain focus to handle user input. Examples: Buttons handle clicks, EditText captures keyboard input. Custom Input Handling: Can override or extend View methods to handle specific input events like touch or key presses. Example: Creating a custom view to draw shapes based on touch. 39 View Listeners for Events: View can register event listeners for specific types of input. Example: A button uses an OnClickListener to detect clicks. Input Dispatching: The View hierarchy processes input events, distributing them to the appropriate child views. 40 2 12/13/2024 Listeners Listeners detect and respond to user actions, such as key presses, or other interactions. How do Listeners Work? A listener acts as a bridge between the View and the logic that handles the event. Common Types of Listeners: Keyboard Input: View.OnKeyListener for handling key events. Touch Input: View.OnTouchListener for responding to touch gestures. Click Events: View.OnClickListener for button clicks. Long Clicks: View.OnLongClickListener for detecting long presses. 41 Listeners Advantages of Using Listeners: Modularity: Separates input-handling logic from the rest of the app. Flexibility: Allows multiple views to handle different inputs simultaneously. Responsiveness: Ensures inputs are processed promptly for a seamless user experience. 42 3 12/13/2024 Summary Input systems include various interaction methods, such as keyboards, touch screens, controllers, and sensors. The View class is central to managing inputs. It acts as the UI component that listens for process events. Listeners provide a structured way to handle specific user actions, making them a core of responsive app desig 43 A Note View will need several attributed in order to work with these listeners In the xml you will need to add android:focusable="true" android:focusableInTouchMode="true" android:clickable="true" 44 4 12/13/2024 Keyboard input 45 View.OnKeyListener is an interface in Android used to listen for keyboard events on a specific View. It helps detect and respond to key press events, such as when a key is pressed down, released, or typed. View.OnKeyListener View.OnKeyListener is an Android interface that listens to keyboard events on a specific View. It helps detect and respond to key press events, such as when a key is pressed down, released, or typed. 46 5 12/13/2024 View.OnKeyListener The primary method is: boolean onKey(View v, int keyCode, KeyEvent event) 47 Handling Key Codes and Events 1.Detecting Key Actions: 1. KeyEvent.ACTION_DOWN: Key is pressed. 2. KeyEvent.ACTION_UP: Key is released. 2.Identifying Keys: 1. Use constants like: 1.KeyEvent.KEYCODE_0: Numeric zero key. 2.KeyEvent.KEYCODE_VOLUME_UP: Volume up button. 48 6 12/13/2024 Implementing a Keyboard Listener for an EditText 49 Implementing a Keyboard Listener for an EditText EditText editText = findViewById(R.id.editText); editText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) { Toast.makeText(getApplicationContext(), "Enter pressed", Toast.LENGTH_SHORT).show(); return true; return false; 50 7 12/13/2024 Advanced Keyboard Handling KeyEvent.KEYCODE_* constants represent specific keys on a device. Examples of Common Key Constants: Alphabet and Numbers: KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_1, etc. Functional Keys: KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_DEL (Delete/Backspace). Special Keys: KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_CAMERA, KeyEvent.KEYCODE_POWER. 51 Example : Capturing the Camera Button Press public boolean onKey(View v, int keyCode, KeyEvent event) if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_CAMERA) Toast.makeText(getApplicationContext(), "Camera button pressed", Toast.LENGTH_SHORT).show(); openCamera(); return true; private void openCamera() { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(cameraIntent); } 52 8 12/13/2024 Example : Capturing the Camera Button Press Key Detection: Detects when the camera button is pressed. User Feedback: Shows a toast message ("Camera button pressed"). Custom Action: Calls the openCamera method to launch the camera app. Event Handling: Prevents the key press from being processed further by returning true. 53 Touch input 54 9 12/13/2024 What is OnTouchListener? OnTouchListener is an interface for listening for touch events on a specific View. It provides a way to detect and respond to touch interactions like pressing, releasing, and moving a finger on a view. 55 OnTouchListener The primary method to implement is: boolean onTouch(View v, MotionEvent event) 56 10 12/13/2024 The MotionEvent Class The MotionEvent class contains detailed information about the touch event. It provides methods to retrieve information like the position of the touch and the type of action performed. 57 The MotionEvent Methods getX() and getY() Returns the X and Y coordinates of the touch event relative to the top-left corner of the view. getRawX() and getRawY() Returns the X and Y coordinates of the touch event relative to the entire screen. getAction() Returns the type of touch action being performed. Common actions include: MotionEvent.ACTION_DOWN: Finger touches the screen. MotionEvent.ACTION_UP: Finger lifts off the screen. MotionEvent.ACTION_MOVE: Finger moves across the screen. MotionEvent.ACTION_CANCEL: The current gesture is canceled. 58 11 12/13/2024 Example 59 Example ImageView imageView = findViewById(R.id.imageView); imageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("TouchEvent", "Touch Down at: (" + event.getX() + ", " + event.getY() + ")"); return true; case MotionEvent.ACTION_MOVE: Log.d("TouchEvent", "Moving at: (" + event.getX() + ", " + event.getY() + ")"); return true; case MotionEvent.ACTION_UP: Log.d("TouchEvent", "Touch Released at: (" + event.getX() + ", " + event.getY() + ")"); return true; return false; 60 12 12/13/2024 Summary of Functionality: ACTION_DOWN: Logs the starting coordinates of the touch. ACTION_MOVE: Logs coordinates as the finger moves. ACTION_UP: Logs the final coordinates when the touch is released. 61 Android Sensors 62 13 12/13/2024 Types of Sensors Motion Sensors Measure acceleration forces and rotational forces. Examples: Accelerometer: Measures acceleration applied to the device along the x, y, and z axes. Gyroscope: Measures the rate of rotation around the device's axes. 63 Types of Sensors Environmental Sensors Measure various environmental parameters. Examples: Light Sensor: Measures ambient light level in lux. Temperature Sensor: Measures ambient air temperature. Pressure Sensor: Measures atmospheric pressure. 64 14 12/13/2024 Types of Sensors Position Sensors Measure physical position or proximity to another object. Examples: Proximity Sensor: Measures the distance of an object from the device. Magnetic Field Sensor: Measures magnetic field strength along the x, y, and z axes. 65 Framework Classes for Sensors SensorManager Role: Accesses device sensors. Registers and unregisters sensor event listeners. Provides constants for sensor accuracy and data acquisition rates. 66 15 12/13/2024 Framework Classes for Sensors Sensor Represents a specific sensor and its properties. Provides information about: Sensor name and type. Maximum range, resolution, and power requirements. 67 Framework Classes for Sensors SensorEvent Provides data from sensors when an event occurs. Contains: sensor: The sensor generating the event. values[]: The data captured by the sensor. accuracy: The accuracy of the event. timestamp: When the event occurred. 68 16 12/13/2024 Framework Classes for Sensors SensorEventListener Interface to receive notifications when: Sensor accuracy changes (onAccuracyChanged). New sensor data is available (onSensorChanged). 69 Example: Accessing and Using a Sensor Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROM ETER); sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); 70 17 12/13/2024 Handle Sensor Data: @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { float x = event.values; float y = event.values; float z = event.values; Log.d("Accelerometer", "X: " + x + ", Y: " + y + ", Z: " + z); 71 18 12/16/2024 Permissions 1 Why are Permissions Required? Role of Permissions as a Gatekeeper User Privacy Protection Transparency and Trust Permissions are displayed in categories: Dangerous permissions Normal permissions Security Against Malicious Apps 2 1 12/16/2024 Examples of Permissions in Action Requesting Camera Access Using Microphone for Audio Recording android.permission.RECORD_AUDIO 3 Dangerous vs Normal Permissions Dangerous Permissions: Require explicit user approval because they involve access to sensitive data or features. Examples: ACCESS_FINE_LOCATION (GPS location). READ_CONTACTS (user’s contact list). RECORD_AUDIO (microphone access). 4 2 12/16/2024 Dangerous vs Normal Permissions Normal Permissions: Do not require user approval; they are automatically granted at installation. These involve lower-risk operations that don’t compromise privacy. Examples: SET_WALLPAPER (change wallpaper). INTERNET (basic internet access). 5 Dangerous vs Normal Permissions Permission Approve Process Example Dangerous User approval needed CAMERA, READ_SMS Normal Auto-granted ACCESS_NETWORK_STATE 6 3 12/16/2024 Saving Data 7 Saving Data what, where, how long, and accessible? Depending on the answers depend on what data-saving method you might use. So, before we get into the technical details of code for each, we need a primer on what each is and how it can be used. 8 4 12/16/2024 Local or remote Firebase provides several storage solutions for storage in the cloud. file, database, etc. Once you have networking, you also have full internet storage options. local bundles sharedpreferences sqlite architecture room (database) files (private or public) preferences (not the same as sharedpreferences) 9 Accessibility local to the app or accessible between apps? Files stored so only the app can access them or public? Content providers Can be created and used on top of sqlite, room, etc to expose data between applications or just between activities/fragements modelview share data between fragments. just in the app sqlite, room, sharedpreferences (but set to not share between activities) 10 5 12/16/2024 Accessibility Between Apps Using ContentProviders A ContentProvider is a key Android component that enables controlled access to app data across different applications. It is an intermediary to securely share data between apps, ensuring only authorized apps can access the shared data. ContentProviders can also manage access to SQLite databases, files, and other persistent storage methods, allowing one app to expose data while maintaining control over how and by whom it is accessed. 11 Why Use ContentProviders? 1.Cross-App Communication: They allow other apps to query, update, or delete data in your app (if permissions are granted). 2.Security: Can define fine-grained access using permission-based rules. 3.Data Abstraction: 1.Apps don’t need to know the underlying data storage mechanism. 12 6 12/16/2024 Key Features of ContentProviders 1.Uniform Interface: Provides a consistent interface (URIs) for accessing data, regardless of storage type. 2.Access Permissions: Define read or write permissions for specific URIs. 3.Cursor-Based Querying: Use cursors to interact with data sets efficiently. 4.Observer Notifications: Notify clients when the data changes, enabling dynamic updates. 13 Examples of Built-In ContentProviders Android provides several built-in ContentProviders for system-level data: ContactsProvider: Access user contacts. MediaStore: Access images, videos, and other media files. CalendarProvider: Access calendar events. 14 7 12/16/2024 temporary or permanent? Temporary Data: Bundles: Ideal for screen rotations or passing data between activities. Destroyed when the application exits. Permanent Data: SharedPreferences: Stores user preferences across app restarts. SQLite and Room Database: Structured and scalable data storage solutions. 15 How much data to store? bundles, sharepreferences, and preferences are intended for very small amounts of data, like values, strings, etc. databases and files can be just about any size. 16 8 12/16/2024 Live data? Some data objects can be set up with observers SQLite uses curser objects that can be notified of change. ContentProviders return cursers so that observers can be set up and notifications made. most of the rest don't have observers, but you can layer the data objects, so you can use a modelview to open a database, file, etc. Set observers from there. Preferences have their screens, so you can use an onResume method to load preferences that may have changed. 17 Dynamic data 18 9 12/16/2024 Screen Rotation When the screen rotates, one of the first things that happens? Where's my data???? This is because in a rotation, the activity onPause(), then onStop(), then onDestory() is called. Once the rotation is complete, onCreate(), onStart(), onResume(). We can deal with a couple of ways. Besides fixing the orientation of the activity. We can use 1 of three ways: bundle, modelview, and sharedpreferences system. 19 Saving Dynamic data. You can also save a "small" amount of dynamic data via a Bundle This actually looks just like we are passing data to the activity. onCreate(Bundle savedInstanceState) Temporary data 20 10 12/16/2024 savedInstanceSate Override public void onSaveInstanceState(Bundle savedInstanceState) void onRestoreInstanceState(Bundle savedInstanceState) But they are not in the Activity Lifecycle, so it possible they will not get called! Use Oncreate() as well. 21 SavedInstance bundle onSaveInstanceState(Bundle) activity event This data will only be held in memory until the application is closed, the data will be available any time that this activity starts within the current lifetime of the application. This is not permanently stored. It's just for this instance of the application. To store data between application instances (ie permanently) use SharedPreferences 22 11 12/16/2024 Storing data Via OnsaveInstanceState and a bundle A bundle has a set of get/put methods for strings, ints, etc.. Using a key and data public void onSaveInstanceState(Bundle savedInstanceState) { String d1 = t1.getText().toString(); savedInstanceState.putString("d1", d1); super.onSaveInstanceState(savedInstanceState); } 23 Storing data Via OnsaveInstanceState and a bundle A bundle has a set of get/put methods for strings, ints, etc.. Using a key and data public void onSaveInstanceState(Bundle savedInstanceState) { String d1 = t1.getText().toString(); savedInstanceState.putString("d1", d1); super.onSaveInstanceState(savedInstanceState); } 24 12 12/16/2024 Restoring data. Via OnCreate(Bundle) if (savedInstanceState != null) { d1 = savedInstanceState.getString("d1"); if (d1 != null) { t1.setText(d1); } } 25 SharedPreferences Generally you want to store Preferences in OnPause() You restore preferences in OnCreate() and/or onPause() Remember onPause() is called after OnCreate() 26 13 12/16/2024 SharedPreferences Also, you can set it up to share per application (ie multiple activities) or per activity. The difference is the how you get the preferences Activity preferences: SharedPreferences preferences = getPreferences(MODE_PRIVATE); Application preferences SharedPreferences preferences = getSharedPreferences(“example",MODE_PRIVATE); Both are private, but there is deprecated MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, MODE_MULTI_PROCESS 27 Storing In OnPause() Super.onPause(); //must be called Get a spot to start the preferences and edit them. SharedPreferences preferences = getPreferences(MODE_PRIVATE); OR SharedPreferences preferences = getSharedPreferences(“example",MODE_PRIVATE); Now set it to editable. SharedPreferences.Editor editor = preferences.edit(); Use the put methods with a key value and then commit them to memory editor.putString("d3",d3); editor.commit(); or editor.apply(); //functionally the same call 28 14 12/16/2024 Restoring Preferences Since, I’m restoring in both onCreate() and OnResume() I’ll use a separate method, called getprefs(); Note in OnResume(), you must call super.OnResume() 29 getPrefs() void getprefs() { Get the between-instance stored values SharedPreferences preferences = getPreferences(MODE_PRIVATE); OR SharedPreferences preferences = getSharedPreferences(“example",MODE_PRIVATE); Now read them back. d3 = preferences.getString("d3", ""); Like preferenceActivity, we set a default value for the key In this case "", if the d3 key doesn’t exist. t3.setText(d3); } 30 15 12/16/2024 Comparison Temporarily vs Permanently Bundle SharedPreferences Data Lifetime Temporary (only during app’s lifecycle). Permanent (persists across app sessions). Use Case Short-term, transient data (e.g., screen rotation). Long-term storage (e.g., user preferences). API Simplicity Simple key-value API for temporary needs. Simple key-value API for persistent storage. Scope Activity-specific or passed between activities. Application-wide (can share across activities). Memory (lost after app or activity is destroyed) Internal app storage (written to disk). Storage Location Performance Lightweight and fast, but temporary. May involve file I/O, but negligible overhead. Example Data Types Strings, integers, etc., for transient storage. Settings, usernames, preferences, etc. Limitations Data lost if the app is terminated. Not ideal for large or frequently updated data. 31 16 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