Android Activity Lifecycle and State Management
41 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What happens to the activity lifecycle when a screen rotation occurs?

  • onStart() is called before onPause().
  • The activity is completely recreated without any lifecycle methods being invoked.
  • onPause(), then onStop(), then onDestroy() are called. (correct)
  • onCreate() is called before onPause() during rotation.
  • Which method can be overridden to save the instance state of an activity?

  • onResume(Bundle savedInstanceState)
  • onSaveInstance(Bundle savedInstanceState)
  • onRestoreInstance(Bundle savedInstanceState)
  • onSaveInstanceState(Bundle savedInstanceState) (correct)
  • Which option describes a way to handle the loss of dynamic data when an activity is recreated?

  • Avoid using any observers for data retrieval.
  • Use Bundles, ModelView, or SharedPreferences to manage the data. (correct)
  • Use SharedPreferences to store all data permanently.
  • Only override onResume() to reload the data.
  • What is a limitation of using saved instance state in Android?

    <p>Data is only held in memory until the application is closed.</p> Signup and view all the answers

    What is a key requirement when using observers with data objects in SQLite?

    <p>Cursors must be set up to notify of data changes.</p> Signup and view all the answers

    Which of the following attributes is NOT required in the XML for a View to work with listeners?

    <p>android:longClickable=&quot;true&quot;</p> Signup and view all the answers

    What method must be implemented to handle keyboard input for a View?

    <p>public boolean onKey(View v, int keyCode, KeyEvent event)</p> Signup and view all the answers

    Which of the following keycodes is used to represent the 'Volume Down' button?

    <p>KeyEvent.KEYCODE_VOLUME_DOWN</p> Signup and view all the answers

    When setting a key listener to an ImageView, which of the following statements is correct?

    <p>iv.setOnKeyListener(new myKeyListener());</p> Signup and view all the answers

    Which method is called when a new key event occurs for an extended View class?

    <p>onKeyDown(int keyCode, KeyEvent event)</p> Signup and view all the answers

    What does the event.getMatch(char[] chars) method return if no characters match?

    <p>' ' character</p> Signup and view all the answers

    Which of the following events provides access to all pushed keys on a View?

    <p>onKeyDown(int keyCode, KeyEvent event)</p> Signup and view all the answers

    To handle trackball motion events in a custom View, which method should be overridden?

    <p>onTrackballEvent(MotionEvent event)</p> Signup and view all the answers

    Which parameter allows determining which key was pressed in the onKey method?

    <p>event.getKeyCode()</p> Signup and view all the answers

    What is the primary role of the SensorManager class?

    <p>To register and unregister sensor event listeners.</p> Signup and view all the answers

    Which of the following accurately describes a SensorEvent?

    <p>It includes data captured during an event, like accuracy and timestamp.</p> Signup and view all the answers

    What function does the SensorEventListener interface serve?

    <p>It notifies when sensor accuracy changes and when new data is available.</p> Signup and view all the answers

    What type of information does the Sensor class provide?

    <p>Sensor name, type, range, and power requirements.</p> Signup and view all the answers

    Which sensor type would be classified as a position sensor?

    <p>Proximity Sensor.</p> Signup and view all the answers

    How does the SensorEvent handle data captured during an event?

    <p>It provides the data in an array format.</p> Signup and view all the answers

    Which aspect is NOT covered by the Sensor class?

    <p>Geographical location of the sensor.</p> Signup and view all the answers

    In which situation would onAccuracyChanged be triggered?

    <p>When there is a change in sensor accuracy.</p> Signup and view all the answers

    What aspect differentiates a proximity sensor from other types?

    <p>It detects the presence of objects without physical contact.</p> Signup and view all the answers

    Which of the following is likely a common limitation of sensor devices?

    <p>Power consumption affecting performance.</p> Signup and view all the answers

    What does the method builder.setSingleChoiceItems() accomplish in the code?

    <p>It sets up a single selection dialog with predefined items.</p> Signup and view all the answers

    Which of the following accurately describes a use case for DialogFragments?

    <p>To manage the dialog's lifecycle effectively in relation to its host fragment.</p> Signup and view all the answers

    In the provided code, which action is taken when an item in the dialog is clicked?

    <p>The dialog is dismissed upon selecting an item.</p> Signup and view all the answers

    What is the primary purpose of the show() method in the context of DialogFragments?

    <p>To display the dialogFragment on the screen.</p> Signup and view all the answers

    What advantage does using DialogFragments provide over AlertDialogs?

    <p>They automatically manage their own fragment lifecycle.</p> Signup and view all the answers

    In the code, which items are included in the items array?

    <p>Remove Walls, Add Walls, Add/Remove Objects, Add/Remove Score</p> Signup and view all the answers

    What does the parameter item represent in the onClick method?

    <p>The index of the selected item in the options list.</p> Signup and view all the answers

    Which listener would you use to respond to a user's multi-touch gesture on a view?

    <p>View.OnTouchListener</p> Signup and view all the answers

    What advantage does modularity provide when using listeners in an application?

    <p>It separates input-handling logic from the rest of the app.</p> Signup and view all the answers

    In a View hierarchy, what is the primary role of input dispatching?

    <p>To distribute input events to the appropriate child views.</p> Signup and view all the answers

    Which listener specifically handles keyboard events in a view?

    <p>View.OnKeyListener</p> Signup and view all the answers

    What can a custom view override or extend to handle touch events more effectively?

    <p>View methods related to input</p> Signup and view all the answers

    What is a potential issue if listeners are not implemented properly in an application?

    <p>Input events may not be processed promptly.</p> Signup and view all the answers

    Which listener would be most appropriate for detecting long presses on a button?

    <p>View.OnLongClickListener</p> Signup and view all the answers

    What kind of events does the View.OnClickListener specifically respond to?

    <p>Click events from buttons</p> Signup and view all the answers

    What is one way that flexibility is enhanced in an application when using listeners?

    <p>By allowing different views to handle different inputs simultaneously.</p> Signup and view all the answers

    Which of the following is NOT a common type of listener?

    <p>View.OnGestureListener</p> Signup and view all the answers

    Study Notes

    Dialogs

    • A dialog is a small window providing additional information without taking up the entire screen.
    • It prompts users for decisions (e.g., Save, Cancel, Exit).
    • Displays additional information (e.g., Progress, Date/Time).

    Dialog Types

    • AlertDialog: Standard dialog with up to three buttons (e.g., Positive, Negative, Cancel).
    • ProgressDialog: Shows 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.

    Creating a Dialog

    • Use AlertDialog.Builder to create a dialog.
    • Can have up to three buttons: positive, negative, and cancel.
    • Set the positive and negative buttons, and disable cancel if needed.

    AlertDialog

    • Instead of standard buttons, can have radio buttons (more than just three).
    • Use Builder.setSingleChoiceltems.
    • Provide a CharSequence array of items.
    • Example item array: {"Remove Walls", "Add Walls", "Add/Remove Objects", "Add/Remove Score"}.

    DialogFragment

    • Instead of using AlertDialog.Builder, use DialogFragment.
    • Implement onCreateDialog(Bundle).
    • Implement onCreateView (optional).
    • DialogFragments can be added to a FrameLayout or use the show() method.

    Why Use DialogFragments?

    • Lifecycle-aware.
    • Better alignment with fragments in modern Android.

    extends DialogFragment and uses AlertDialog

    • Code example demonstrating a dialog fragment and its use of AlertDialog.Builder.

    Input

    • Keyboard, touch, controllers, and device sensors.

    View

    • For input, add a custom listener to a View class.
    • EditText has a keyboard listener.
    • Can't have a listener for a "screen" (unless it takes up the entire screen).
    • Sensor is an exception.

    A Note

    • Views need attributes to work with listeners.
    • Add android:focusable="true", android:focusableInTouchMode="true", android:clickable="true" in XML.

    View.OnKeyListener

    • For keyboard input, implement View.OnKeyListener.
    • Override the onKey() method.
    • Accesses key events (e.g., keyCode, KeyEvent event).

    View.OnKeyListener (Details)

    • Determines which key has been pressed.
    • Uses event.getMatch(char[] chars) to check if a character matches a set of characters.
    • Uses KeyEvent.Constants for various key codes (e.g., KEYCODE_0, KEYCODE_CAMERA).
    • Gives access to keys pressed (e.g., KEYCODE_CAMERA, KEYCODE_ENDCALL).

    View.OnKeyListener (Adding Listener)

    • Add listener to the view (e.g., ImageView).
    • iv.setOnKeyListener(new myKeyListener()).

    View Overrides

    • Extending View allows overriding several methods.
    • 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.

    Touch Input

    • Uses OnTouchListener.
    • OnTouchListener can be used, along with OnClickListener and OnLongClickListener for button functionality.

    View.OnTouchListener

    • Override onTouch(View v, MotionEvent event) for touch events on a view.
    • Returns true if the event is consumed, false otherwise.
    • Retrieve touch event coordinates (getX(), getY(), getRawX(), getRawY()) and action (getAction()).

    The MotionEvent Class

    • Contains detailed information about the touch event.
    • Provides methods for getting touch coordinates and action types (e.g., getX(), getY(), getAction()).
    • Common actions include ACTION_DOWN, ACTION_MOVE, ACTION_UP, and ACTION_CANCEL.

    Defining Input Systems in Android

    • Keyboard Input: Typing in EditText.
    • Touch Input: Swipes, long presses, multi-touch.
    • Device Sensors: Detecting orientation, steps.

    View (Listeners and Handling)

    • Plays a central role in handling input.
    • Focus and Interaction: Views can gain focus for input.
    • Custom Input Handling: Can override view methods to handle specific input events.
    • Listeners for Events: Views register event listeners for various inputs (e.g., OnClickListener for clicks).
    • Input Dispatching: View hierarchy processes events and distributes them to the appropriate child views.

    Listeners

    • Listeners detect and respond to user actions (e.g., key presses).
    • act as a bridge between Views and logic handling those events.
    • Types of Listeners:
      • Keyboard Input: View.OnKeyListener
      • Touch Input: View.OnTouchListener
      • Click Events: View.OnClickListener
      • Long Clicks: View.OnLongClickListener

    Listeners (Advantages)

    • Modularity: Separates input handling from the rest of the app.
    • Flexibility: Multiple views can handle various inputs simultaneously.
    • Responsiveness: Ensures input is processed quickly.

    Summary

    • Input systems encompass various interaction methods (keyboard, touch, sensors).
    • Views manage inputs as the UI component listening for events.
    • Listeners provide a structured way handle actions.

    A Note

    • Views need attributes to work with listeners (focusable, focusableInTouchMode, clickable).
    • These attributes go in XML layout files.

    Keyboard Input

    • View.OnKeyListener interface listens to keyboard events on a specific View.
    • Handles key press events (down, up, type).

    View.OnKeyListener (Method)

    • The primary method is boolean onKey(View v, int keyCode, KeyEvent event).

    Handling Key Codes and Events

    • KeyEvent.ACTION_DOWN: Key pressed.
    • KeyEvent.ACTION_UP: Key released.
    • Constants like KEYCODE_0, KEYCODE_VOLUME_UP for specific keys.

    Implementing a Keyboard Listener for an EditText

    • Code example showing how to add a keyboard listener to an EditText.

    Advanced Keyboard Handling

    • KeyEvent.KEYCODE_* constants represent specific keys on a device.
    • Examples of common key constants: alphabet, numbers, function keys, special keys.

    Example: Capturing the Camera Button Press

    • Detects when the camera button is pressed.
    • Shows a toast message.
    • Calls openCamera method to launch camera app.

    Touch Input

    • OnTouchListener interface is used to listen to touch events.
    • Provides methods for detecting events like pressing, releasing, and moving a finger.

    The MotionEvent Class(2)

    • Contains detailed info about touch events (position, type of action).
    • Methods for getting touch coordinates (getX(), getY(), getRawX(), getRawY()), action (getAction).

    Example (Touch)

    • Code example demonstrating use of OnTouchListener to log touch actions (DOWN, MOVE, UP).

    Summary of Functionality (Touch)

    • ACTION_DOWN, ACTION_MOVE, and ACTION_UP.
    • Starting and final touch coordinates, and coordinates during movement displayed.

    Android Sensors

    • Motion Sensors: Measure acceleration and rotation.
    • Environmental Sensors: Measure attributes such as light, temperature, pressure.
    • Position Sensors: Measure physical position or proximity (e.g., proximity, magnetic field).

    Framework Classes for Sensors (1)

    • SensorManager: Manages accessing and registering sensor listeners.

    Framework Classes for Sensors (2)

    • Sensor: Represents a specific sensor, including properties like name, type, max range, res, required power.

    Framework Classes for Sensors (3)

    • SensorEvent: Contains raw sensor data when an event occurs. Provides sensor, values[], accuracy, and timestamp.

    Framework Classes for Sensors (4)

    • SensorEventListener: Interface for receiving events from sensors such as accuracy changing, or when new data is available.

    Example: Accessing and Using a Sensor

    • Code example for accessing and using a sensor (like an accelerometer).

    Handle Sensor Data

    • Override the onSensorChanged() method to handle sensor events.

    Permissions

    • Role of Permissions as a Gatekeeper for user privacy.
    • Transparency and Trust: Permissions categorized (Dangerous or Normal).
    • Security against malicious apps.
    • Permissions are usually explicit user approval.

    Examples of Permissions in Action

    • Example code for requesting camera and audio recording permissions.

    Dangerous vs Normal Permissions

    • Explicit user approval is essential for "Dangerous Permissions".
    • Examples: ACCESS_FINE_LOCATION, READ_CONTACTS, RECORD_AUDIO.
    • "Normal Permissions" are automatically granted.
    • Examples: SET_WALLPAPER, INTERNET.

    Saving Data

    • Discusses considerations for how long input data should be kept and where it should be stored.
    • Different storage methods, like local storage (files, databases, etc.) and remote storage (cloud services, etc.), have different implications for data permanence, accessibility, and cost-benefit ratio.

    Local or Remote Storage

    • Firebase, file/database, and other cloud storage.
    • Bundle, prefs, and Sqlite as local storage.

    Accessibility

    • Local app-only storage.
    • Storage accessible between apps via content providers if authorized.

    Accessibility Between Apps Using ContentProviders

    • ContentProviders act as an intermediary for secure app-to-app data access.

    Key Features of ContentProviders

    • Uniform interface (URIs): Consistent interface for accessing data regardless of storage type
    • Access permissions: Defining read/write permissions for specific URIs
    • Cursor-based querying: Efficient data set interaction using cursors
    • Observer notifications: Notifying clients of data changes

    Examples of Built-In ContentProviders

    • ContactsProvider, MediaStore, CalendarProvider

    Temporary or Permanent Storage

    • Temporary: Bundles (for short-term needs like screen rotation)
    • Permanent: SharedPreferences (for persistent data like user preferences), SQLite or database for more complex needs.

    Live Data

    • Relevant data objects are set up with observers to handle changes (e.g., in databases).
    • ContentProviders provide cursers to aid in tracking changes to data objects.
    • Preferences have event handling for when changes occur for data to be tracked.

    Screen Rotation

    • Screen rotations cause actions in the activity lifecycle (onPause, onStop, onDestroy, onCreate, onStart, onResume).
    • Bundles can help preserve data during rotation.

    Saving Dynamic Data

    • Passing data through a bundle (onCreate(Bundle)).
    • To use Bundles, they must be included in the activities onCreate and are then used to pass data in/out of activities.

    savedInstanceState

    • Override methods for saving and restoring state during possible app lifecycle events
    • Method onSaveInstanceState of the relevant activity to save data temporarily.
    • Method onRestoreInstanceState of the relevant activity to retrieve data on application restart.

    Shared Preferences

    • Used for storing simple persistent data between app restarts.

    Shared Preferences (Setup and use)

    • Using shared preferences to store and retrieve data.

    Restoring Preferences

    • Instructions on how to read data loaded in shared preferences.

    Comparison Temporary vs Permanently

    • Comparison table for various methods of data storage (Bundles, SharedPreferences, databases).
    • Bundles are ideal for very small amounts of data, while shared Preferences are more suitable when larger amounts of data are needed.

    Firebase

    • Client-side development platform built on Google Cloud.
    • Comprehensive set of tools for building and running apps.

    Firebase Setup

    • Adding, configuring, and using Firebase in a project.

    Firebase Build Category

    • Managed Infrastructure: Tools for protecting resources.
    • Hosting: For hosting apps (static and dynamic).
    • Authentication: Simplifying user login and onboarding.

    Firebase Run Category

    • Crashlytics: A crash reporting tool.
    • Google Analytics: For analyzing user behavior.
    • Cloud Messaging: Push notifications for apps.
    • In-App Messaging: For contextual messages within your app.

    Firebase Console

    • Web interface for controlling Firebase.

    Cloud Messaging

    • Push notifications (using tokens) that don't require polling for messages (and thus conserve device battery).

    In-app Messaging

    • Messages displayed directly within the application, instead of external notifications.

    Remote Config

    • Method to update/deploy changes in your app without requiring new app versions.

    Authentication

    • Firebase Authentication service for handling user logins with various providers (email/password, Google, Facebook, etc.).

    Database

    • Firestore and Realtime Databases.
    • Realtime database stores and synchronizes data between clients.

    Database Setup

    • Setting up Firebase Database and Firestore connections in your android project.

    Cloud Firestore

    • A NoSQL, cloud database for quick and resilient querying.
    • Includes collections, documents, and subcollections for hierarchical data structures.
    • Allows both realtime and offline support for data.

    Getting Started with Firestore

    • Instructions for setting up and using Firestore.

    Add Data

    • Instructions for adding data to Firestore.

    Retrieving Data

    • Instructions for getting data from Firestore.

    Retrieving Multiple Documents

    • Using a listener for retrieving multiple documents.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Dialogs PDF

    Description

    Test your knowledge on the Android activity lifecycle, including what happens during screen rotations and how to save instance states. This quiz also covers handling dynamic data loss and best practices when using observers with SQLite data objects.

    More Like This

    Android Application Development Concepts
    11 questions
    Android Activity Lifecycle
    17 questions

    Android Activity Lifecycle

    AdaptiveMoldavite7334 avatar
    AdaptiveMoldavite7334
    Android Activity Lifecycle
    29 questions

    Android Activity Lifecycle

    VersatileEinsteinium avatar
    VersatileEinsteinium
    Android Activity Lifecycle Quiz
    21 questions
    Use Quizgecko on...
    Browser
    Browser