Android Input Systems (PDF)
Document Details
Uploaded by Deleted User
Tags
Summary
This document provides a summary of input systems in Android, covering different interaction methods like keyboards, touchscreens, and device sensors. It explains the role of Views, Listeners and various sensor types including motion and environmental sensors. The document is intended for readers learning about Android programming.
Full Transcript
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-...
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