The path to Android development and learning-sensor experience

Source: Internet
Author: User

The path to Android development and learning-sensor experience

There are still many sensors, such as acceleration, light, and magnetic sensors. Of course, android phones are called smartphones, and these sensors are indispensable. Next I will learn about light, acceleration, and magnetism.

Create an emSensorStudy project. The layout is as follows:

<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical" android: layout_margin = "5dp" tools: context = "com. jared. emsensorsstudy. mainActivity "> <textview android: text =" Hello Sensors "android: layout_gravity =" center "android: layout_width =" wrap_content "android: layout_height =" wrap_content "android: textsize = "22dp"> <button android: id = "@ + id/startLightSensor" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "Start LightSensor" android: textallcaps = "false"> </button> <button android: id = "@ + id/startAccelerSensor" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "enable AccelerSensor" android: textallcaps = "false"> </button> <button android: id = "@ + id/startMagneticSensor" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "Start MagneticSensor" android: textallcaps = "false"> </button> </textview> </linearlayout>
Add the LightSensor, AccelerSensor, and MagnetiSensor Activity. Modify the MainActivity Code as follows:
package com.jared.emsensorsstudy;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity {    private Button startLightSensorBtn;    private Button startAccelerSensorBtn;    private Button startMagneticSensorBtn;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        startLightSensorBtn = (Button)findViewById(R.id.startLightSensor);        startAccelerSensorBtn = (Button)findViewById(R.id.startAccelerSensor);        startMagneticSensorBtn = (Button)findViewById(R.id.startMagneticSensor);        startLightSensorBtn.setOnClickListener(new myOnClickListener());        startAccelerSensorBtn.setOnClickListener(new myOnClickListener());        startMagneticSensorBtn.setOnClickListener(new myOnClickListener());    }    private class myOnClickListener implements View.OnClickListener {        @Override        public void onClick(View view) {            switch (view.getId()) {                case R.id.startAccelerSensor:                    Intent intent1 = new Intent(getApplicationContext(), AccelerSensor.class);                    startActivity(intent1);                    break;                case R.id.startLightSensor:                    Intent intent2 = new Intent(getApplicationContext(), LightSensor.class);                    startActivity(intent2);                    break;                case R.id.startMagneticSensor:                    Intent intent3 = new Intent(getApplicationContext(), MagneticSensor.class);                    startActivity(intent3);                    break;                default:                    break;            }        }    }}

First, you must implement the Light function. First, modify the layout as follows:
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" tools:context="com.jared.emsensorsstudy.LightSensor">    <textview android:id="@+id/light_level" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textsize="22dp"></textview></linearlayout>

A textview is implemented to display the illumination intensity. Then modify the LightSensor Code as follows:
package com.jared.emsensorsstudy;import android.content.Context;import android.hardware.Sensor;import android.hardware.SensorEvent;import android.hardware.SensorEventListener;import android.hardware.SensorManager;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.widget.TextView;public class LightSensor extends AppCompatActivity {    private SensorManager sensorManager;    private TextView lightLevel;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_light_sensor);        lightLevel = (TextView)findViewById(R.id.light_level);        initWithLight();    }    @Override    protected void onDestroy() {        super.onDestroy();        if(sensorManager != null) {            sensorManager.unregisterListener(listener);        }    }    public void initWithLight() {        sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);    }    private SensorEventListener listener = new SensorEventListener() {        @Override        public void onSensorChanged(SensorEvent sensorEvent) {            float value = sensorEvent.values[0];            lightLevel.setText("Currrent light level is "+value+"lx");        }        @Override        public void onAccuracyChanged(Sensor sensor, int i) {        }    };}
Here, get the sensor through getSystemService, and then register a listener to listen to the sensor changes. When the value changes, the onSensorChanged method is called. After the operation, the sensor near the receiver is shielded by hand, shown as follows:

The effect of visible light is obvious. Next we will try the acceleration sensor. Here, the shake function is implemented and the vibration is successful.

Modify the layout as follows:

<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical" android: layout_margin = "10dp" tools: context = "com. jared. emsensorsstudy. accelerSensor "> <textview android: Layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "Shake it to get more! "Android: layout_gravity =" "android: textsize =" 22dp "> <textview android: id =" @ + id/shack "android: layout_width =" wrap_content "android: layout_height = "wrap_content" android: layout_gravity = "center" android: textsize = "22dp"> </textview> </linearlayout>

Add the following code:
Package com. jared. emsensorsstudy; import android. content. context; import android. hardware. sensor; import android. hardware. sensorEvent; import android. hardware. sensorEventListener; import android. hardware. sensorManager; import android. OS. bundle; import android. OS. vibrator; import android. support. v7.app. appCompatActivity; import android. widget. textView; public class AccelerSensor extends AppCompatActivity {pr Ivate SensorManager sensorManager; private TextView shackPhone; private Vibrator vibrator; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_acceler_sensor); shackPhone = (TextView) findViewById (R. id. shack); initWithAcceler () ;}@ Override protected void onDestroy () {super. onDestroy (); if (sensorManager! = Null) {sensorManager. unregisterListener (listener);} private void initWithAcceler () {sensorManager = (SensorManager) getSystemService (Context. SENSOR_SERVICE); Sensor sensor = sensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER); sensorManager. registerListener (listener, sensor, SensorManager. SENSOR_DELAY_NORMAL); vibrator = (Vibrator) getSystemService (Context. VIBRATOR_SERVICE);} private Se NsorEventListener listener = new SensorEventListener () {@ Override public void onSensorChanged (SensorEvent sensorEvent) {float xValue = Math. abs (sensorEvent. values [0]); float yValue = Math. abs (sensorEvent. values [1]); float zValue = Math. abs (sensorEvent. values [2]); int medumValue = 19; if (xValue> medumValue | yValue> medumValue | zValue> medumValue) {vibrator. vibrate (200); shackPhone. setText ("Congratulations! You have a successful shake and a happy New Year! ");} Else {// Toast. makeText (getApplicationContext ()," Shake it up! ", Toast. LENGTH_SHORT). show () ;}@ Override public void onAccuracyChanged (Sensor sensor, int I ){}};}

The code here is similar to the LightSensor code, mainly when the acceleration in the three directions is greater than 19, it means that it is shaking, and then it is OK to shake the phone. The effect is as follows:

Finally, I want to learn about magneticSensor. Compass is implemented here. The first step is to provide an image. Modify the layout as follows:

<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" tools:context="com.jared.emsensorsstudy.MagneticSensor">    <imageview android:id="@+id/compass_img" android:layout_width="250dp" android:layout_height="250dp" android:layout_centerinparent="true" android:src="@drawable/compass"></imageview></relativelayout>

Then the MagneticSensor code is modified:

Package com. jared. emsensorsstudy; import android. content. context; import android. hardware. sensor; import android. hardware. sensorEvent; import android. hardware. sensorEventListener; import android. hardware. sensorManager; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. view. animation. animation; import android. view. animation. rotateAnimation; import android. widget. imageView; public class MagneticSensor extends AppCompatActivity {private SensorManager sensorManager; private ImageView compassImage; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_magnetic_sensor); compassImage = (ImageView) findViewById (R. id. compass_img); initWithCompass () ;}@ Override protected void onDestroy () {super. onDestroy (); sensorManager. unregisterListener (listener);} private void initWithCompass () {sensorManager = (SensorManager) getSystemService (Context. SENSOR_SERVICE); Sensor magneticSensor = sensorManager. getdefasensensor (Sensor. TYPE_MAGNETIC_FIELD); Sensor acclerSensor = sensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER); sensorManager. registerListener (listener, magneticSensor, SensorManager. SENSOR_DELAY_GAME); sensorManager. registerListener (listener, acclerSensor, SensorManager. SENSOR_DELAY_GAME);} private SensorEventListener listener = new SensorEventListener () {float [] acclerValues = new float [3]; float [] magneticValues = new float [3]; private float listener; @ Override public void onSensorChanged (SensorEvent sensorEvent) {switch (sensorEvent. sensor. getType () {case Sensor. TYPE_ACCELEROMETER: acclerValues = sensorEvent. values. clone (); break; case Sensor. TYPE_MAGNETIC_FIELD: magneticValues = sensorEvent. values. clone (); break; default: break;} float [] values = new float [3]; float [] R = new float [9]; // call getRotaionMatrix to obtain the transformation matrix R [] SensorManager. getRotationMatrix (R, null, acclerValues, magneticValues); SensorManager. getOrientation (R, values); // passed by SensorManager. getOrientation (R, values); The obtained values value is radian // converted to float rotateDegree =-(float) Math. toDegrees (values [0]); if (Math. abs (rotateDegree-lastRotateDegree)> 2) {RotateAnimation animation = new RotateAnimation (lastRotateDegree, rotateDegree, Animation. RELATIVE_TO_SELF, 0.5f, Animation. RELATIVE_TO_SELF, 0.5f); animation. setFillAfter (true); compassImage. startAnimation (animation); lastRotateDegree = rotateDegree; }}@ Override public void onAccuracyChanged (Sensor sensor, int I ){}};}

Here, acceleration and magnetic sensors are used to achieve one direction, because direction sensors are not officially recommended. The running effect is as follows:

The sensor learns this first.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.