10.10 Sensor Topic (1) - Introduction
Classification Android Basic Tutorial
1. Introduction to Sensors:
When it comes to sensors, I believe everyone is familiar with them. For example, WeChat's shake feature uses the accelerometer sensor;
Definition of Sensor: A physical device or biological organ that can detect and sense external signals, physical conditions (such as light, heat, humidity) or chemical compositions (such as smoke), and transmit the detected information to other devices or organs!
Types of Sensors: Sensors can be categorized from different perspectives, such as conversion principles (the basic physical or chemical effects of sensor operation); applications; output signals; and materials and processes used. Generally, they are classified by their working principles: physical sensors and chemical sensors. The sensors on mobile phones are mostly physical sensors. The sensors on mobile phones include:
-Orientation Sensor
-Accelerometer Sensor
-Gyroscope Sensor
-Magnetic Field Sensor
-Proximity Sensor
-Light Sensor
-Pressure Sensor
-Temperature Sensor
-Gravity Sensor (introduced in Android 2.3)
-Linear Acceleration Sensor (introduced in Android 2.3)
-Rotation Vector Sensor (introduced in Android 2.3)
-Relative Humidity Sensor (introduced in Android 4.0)
-Near Field Communication (NFC) Sensor (introduced in Android 2.3), NFC is different from others as it has read and write capabilities.
Of course, there are other sensors such as heart rate sensors, pedometer sensors, fingerprint sensors, etc. For the types of sensors supported by Android devices, see the official documentation: Sensor Summary section.
2. How to Check Which Sensors Your Phone Supports:
Not all the sensors mentioned above are available on every phone. The types and number of sensors on each phone may vary. For example, the Nexus 5 I have supports sensors like gravity, light, proximity, pressure, and gyroscope! While the Moto X二代 has gravity, light, proximity, and infrared sensors! To find out which sensors your phone supports, you can search for your model on relevant review websites like ZOL Mobile Online, Pacific, etc., to check the related parameters. Of course, we can also write code to see which sensors our phone supports.
Code Example:
Running Effect Diagram:
Code Implementation:
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/txt_show"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</ScrollView>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TextView txt_show;
private SensorManager sm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
txt_show = (TextView) findViewById(R.id.txt_show);
List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
StringBuilder sb = new StringBuilder();
sb.append("This phone has " + allSensors.size() + " sensors, including:\n\n");
for(Sensor s:allSensors){
switch (s.getType()){
case Sensor.TYPE_ACCELEROMETER:
sb.append(s.getType() + " Accelerometer Sensor" + "\n");
break;
case Sensor.TYPE_GYROSCOPE:
sb.append(s.getType() + " Gyroscope Sensor" + "\n");
break;
case Sensor.TYPE_LIGHT:
sb.append(s.getType() + " Light Sensor" + "\n");
break;
case Sensor.TYPE_MAGNETIC_FIELD:
sb.append(s.getType() + " Magnetic Field Sensor" + "\n");
break;
case Sensor.TYPE_ORIENTATION:
sb.append(s.getType() + " Orientation Sensor" + "\n");
break;
case Sensor.TYPE_PRESSURE:
sb.append(s.getType() + " Pressure Sensor" + "\n");
break;
case Sensor.TYPE_PROXIMITY:
sb.append(s.getType() + " Proximity Sensor" + "\n");
break;
case Sensor.TYPE_TEMPERATURE:
sb.append(s.getType() + " Temperature Sensor" + "\n");
break;
default:
sb.append(s.getType() + " Other Sensor" + "\n");
break;
}
sb.append("Device Name: " + s.getName() + "\nVersion: " + s.getVersion() + "\nVendor: "
+ s.getVendor() + "\n\n");
}
txt_show.setText(sb.toString());
}
}
3. Sensor-Related Methods and Usage Patterns
From the example in section 2, we can roughly summarize the process of obtaining Sensor sensors and some related information as follows:
1) Sensor-Related Methods
Step 1: Obtain the Sensor Manager:
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
Step 2: Obtain a list of sensor objects for the device:
List<Sensor> allSensors = sm.getSensorList(Sensor.TYPE_ALL);
Step 3: Iterate to get the Sensor object, and then call the corresponding methods to get the sensor's information:
for(Sensor s:allSensors){
sensor.getName(); // Get sensor name
sensor.getType(); // Get sensor type
sensor.getVendor(); // Get sensor vendor
sensor.getVersion(); // Get sensor version
sensor.getResolution(); // Get accuracy value
sensor.getMaximumRange(); // Get maximum range
sensor.getPower(); // Get power consumption when using the sensor
}
2) Sensor Usage Patterns
Generally, we rarely directly obtain the Sensor and then get the above information. This has little practical use. We are more interested in obtaining the data collected by the sensors, such as the current atmospheric pressure, or the values of the three angles of the orientation sensor, or the values of the gyroscope, etc. The routine for most sensor data collection is as follows:
~Step 1: Obtain the Sensor Manager:
SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);
~Step 2: Call a specific method to obtain the desired sensor:
For example, here we obtain the orientation sensor. Check the API for the sensor you want:
Sensor mSensorOrientation = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
~Step 3: Implement the SensorEventListener interface and override the onSensorChanged and onAccuracyChanged methods:
onSensorChanged: Called when the sensor value changes
@Override
public void onSensorChanged(SensorEvent event) {
// Handle sensor data changes
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// Handle sensor accuracy changes
}
onAccuracyChanged: Callback when the sensor's accuracy changes.
@Override
public void onSensorChanged(SensorEvent event) {
final float[] _Data = event.values;
this.mService.onSensorChanged(_Data[0], _Data[1], _Data[2]);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
We typically obtain sensor data from the SensorEvent. This class has a values variable, which is of type Float[]. This variable has a maximum of three elements, and the meaning of each element varies depending on the sensor. For example, in the orientation sensor, the first element represents the azimuth value, while in the barometric sensor, the first value represents the atmospheric pressure!
~Step 4: Register the listener with the SensorManager object:
ms.registerListener(mContext, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);
The method is straightforward with the following parameters: context object, Sensor object, and sensor delay time precision. There are four optional values:
- SENSORDELAYFASTEST — Delay: 0ms
- SENSORDELAYGAME — Delay: 20ms
- SENSORDELAYUI — Delay: 60ms
- SENSORDELAYNORMAL — Delay: 200ms
Lower delay means more frequent checks and higher power consumption. Unless high precision is required, it is generally recommended to use the third option. Consider your needs carefully.
~Step 5: Unregister the listener:
It's a good practice to unregister the listener when done, typically in the destruction method of an Activity or Service:
ms.registerListener(mContext, mSensorOrientation, android.hardware.SensorManager.SENSOR_DELAY_UI);
The process is quite simple.
4. Sample Code Download:
Summary:
This section introduced Android sensors and how to determine which sensors your phone supports. You can either look it up online or write code to test. It also covered the process of obtaining sensor-related information and the routine for collecting sensor data. Further discussions on the usage of common sensors will follow. Stay tuned.
-1.0 Android Basic Beginner Tutorial
-1.0.1 2015 Latest Android Basic Beginner Tutorial Table of Contents
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Setup
-1.2.1 Developing Android APP with Eclipse + ADT + SDK
-1.2.2 Developing Android APP with Android Studio
-1.3 Solving SDK Update Issues
-1.4 Genymotion Emulator Installation
-1.5.1 Git Tutorial for Basic Local Repository Operations
-1.5.2 Using GitHub to Set Up a Remote Repository
-1.6 How to Use 9-Patch Images
-1.7 Interface Prototype Design
-1.8 Project Source Analysis (Various Files, Resource Access)
-1.9 Android Program Signing and Packaging
-1.11 Decompiling APK to Obtain Code & Resources
-2.1 Concepts of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-2.2.2 RelativeLayout (Relative Layout)
-2.2.3 TableLayout (Table Layout)
-2.2.4 FrameLayout (Frame Layout)
-2.2.5 GridLayout (Grid Layout)
-2.2.6 AbsoluteLayout (Absolute Layout)
-2.3.1 Detailed Explanation of TextView (Text Box)
-2.3.2 Detailed Explanation of EditText (Input Box)
-2.3.5.RadioButton (Radio Button) & Checkbox (Checkbox)
-2.3.6 ToggleButton and Switch
-2.3.7 ProgressBar (Progress Bar)
-2.3.9 RatingBar (Star Rating Bar)
-2.4.1 ScrollView (Scroll Bar)
-2.4.2 Date & Time Components (Part 1)
-2.4.3 Date & Time Components (Part 2)
-2.4.5 Simple Usage of ListView
-2.4.6 Optimization of BaseAdapter
-2.4.7 Focus Issues with ListView
-2.4.8 Solving Checkbox Misalignment in ListView
-2.4.9 Data Update Issues with ListView
-2.5.0 Building a Reusable Custom BaseAdapter
-2.5.1 Implementing Multiple Item Layouts in ListView
-2.5.2 Basic Usage of GridView (Grid View)
-2.5.3 Basic Usage of Spinner (List Option Box)
-2.5.4 Basic Usage of AutoCompleteTextView (Auto-Complete Text Box)
-2.5.5 Basic Usage of ExpandableListView (Collapsible List)
-2.5.6 Basic Usage of ViewFlipper (Flip View)
-2.5.8 Detailed Explanation of Notification (Status Bar Notification)
-2.5.9 Detailed Explanation of AlertDialog (Dialog Box)
-2.6.0 Basic Usage of Other Common Dialogs
-2.6.1 Basic Usage of PopupWindow (Floating Box)
-2.6.3 Simple Usage of ViewPager
-2.6.4 Simple Usage of DrawerLayout (Official Side Menu)
-3.1.1 Event Handling Mechanism Based on Listening
-3.2 Event Handling Mechanism Based on Callback
-3.3 Analysis of Handler Message Passing Mechanism
- 3.4 TouchListener vs OnTouchEvent + Multi-touch
- 3.5 Listening to EditText Content Changes
- 3.6 Responding to System Settings Events (Configuration Class)
- 3.7 AsyncTask Asynchronous Tasks
- 3.8 Gestures
- 4.1.1 Activity Beginner
- 4.1.2 Activity Intermediate
- 4.1.3 Activity Advanced
- 4.2.1 Service Beginner
- 4.2.2 Service Intermediate
- 4.2.3 Service Advanced
- 4.3.1 BroadcastReceiver Beginner
- 4.3.2 BroadcastReceiver Intermediate
- 4.4.1 ContentProvider Beginner
- 4.4.2 ContentProvider Intermediate - Document Provider
- 4.5.1 Basic Usage of Intent
- 4.5.2 Passing Complex Data with Intent
- 5.1 Fragment Basic Overview
- 5.2.1 Fragment Example Analysis - Bottom Navigation Bar Implementation (Method 1)
- 5.2.2 Fragment Example Analysis - Bottom Navigation Bar Implementation (Method 2)
- 5.2.3 Fragment Example Analysis - Bottom Navigation Bar Implementation (Method 3)
- 5.2.4 Fragment Example Analysis - Bottom Navigation Bar + ViewPager Swipe to Switch Pages
- 5.2.5 Fragment Example Analysis - Simple Implementation of News (Shopping) App List Fragment
- 6.1 Data Storage and Access - File Storage and Reading/Writing
- 6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
- 6.3.1 Data Storage and Access - Introduction to SQLite Database
- 6.3.2 Data Storage and Access - Further Exploration of SQLite Database
- 7.1.1 Android Network Programming Essentials and HTTP Protocol Study
- 7.1.2 Android HTTP Request Headers and Response Headers Study
- 7.1.3 Android HTTP Request Method: HttpURLConnection
- 7.1.4 Android HTTP Request Method: HttpClient
- 7.2.1 Android XML Data Parsing
- 7.2.2 Android JSON Data Parsing
- 7.3.1 Android File Upload
- 7.3.2 Android File Download (1)
- 7.3.3 Android File Download (2)
- 7.4 Android Calling WebService
- 7.5.1 WebView (Web View) Basic Usage
- 7.5.2 WebView and JavaScript Interaction Basics
- 7.5.3 WebView Considerations After Android 4.4
- 7.5.4 WebView File Download
- 7.5.5 WebView Cache Issues
- 7.5.6 WebView Handling Webpage Error Code Information
- 7.6.1 Socket Network Basics Preparation
- 7.6.2 TCP Protocol Based Socket Communication (1)
- 7.6.3 TCP Protocol Based Socket Communication (2)
- 7.6.4 UDP Protocol Based Socket Communication
- 8.1.1 13 Drawable Types in Android Summary Part 1
- 8.1.2 13 Drawable Types in Android Summary Part 2
- 8.1.3 13 Drawable Types in Android Summary Part 3
- 8.2.1 Bitmap (Bitmap) Comprehensive Analysis Part 1
- 8.2.2 Bitmap OOM Issues
- 8.3.1 Detailed Explanation of Three Drawing Tool Classes
- 8.3.2 Drawing Class Practical Examples
- 8.3.3 Paint API - MaskFilter (Mask)
- 8.3.4 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 1)
- 8.3.5 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 2)
- 8.3.6 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 3)
- 8.3.7 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 4)
- 8.3.8 Paint API - Xfermode and PorterDuff Detailed Explanation (Part 5)
- 8.3.9 Paint API - ColorFilter (Color Filter) (1/3)
- 8.3.10 Paint API - ColorFilter (Color Filter) (2/3)
- 8.3.11 Paint API - ColorFilter (Color Filter) (3/3)
- 8.3.12 Paint API - PathEffect (Path Effect)
- 8.3.13 Paint API - Shader (Image Rendering)
- 8.3.14 Paint Enum/Constants and ShadowLayer Shadow Effect
- 8.3.15 Paint API - Typeface (Font Style)
- 8.3.16 Canvas API Detailed Explanation (Part 1)
- 8.3.17 Canvas API Detailed Explanation (Part 2) Clipping Methods Collection
- 8.3.18 Canvas API Detailed Explanation (Part 3) Matrix and drawBitmapMesh
- 8.4.1 Android Animation Collection - Frame Animation
- 8.4.2 Android Animation Collection - Tween Animation
- 8.4.3 Android Animation Collection - Property Animation - Introduction
- 8.4.4 Android Animation Collection - Property Animation - Further Exploration
- 9.1 Using SoundPool to Play Sound Effects (Duang~)
10.10 Sensor Topics (1) – Introduction
11.0《2015 Latest Android Basic Beginner's Tutorial》Completion Celebration~
12.2 DrySister Viewing Girls App (Version 1) – 2. Parsing Backend Data
12.4 DrySister Viewing Girls App (Version 1) – 4. Adding Data Caching (Incorporating SQLite)