Android開發學習之路--感應器之初體驗

來源:互聯網
上載者:User

Android開發學習之路--感應器之初體驗

說到感應器,還是有很多的,有加速度啊,光照啊,磁感應器等等。當然android手機之所以稱為智能手機,少不了這幾款感應器的功勞了。下面就學習下了,這裡主要學習光照,加速度和磁。

建立工程emSensorStudy,布局如下:

<!--{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: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="啟動LightSensor" android:textallcaps="false"></button><button android:id="@+id/startAccelerSensor" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動AccelerSensor" android:textallcaps="false"></button><button android:id="@+id/startMagneticSensor" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="啟動MagneticSensor" android:textallcaps="false"></button></textview></linearlayout>
添加LightSensor,AccelerSensor,MagnetiSensor的Activity,修改MainActivity代碼如下:
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;            }        }    }}

先要實現Light的功能,先修改布局如下:
<!--{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>

簡單地實現了一個textview用來顯示光線照強度。接著修改LightSensor代碼如下:
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) {        }    };}
這裡先通過getSystemService擷取sensor,然後通過註冊一個listener來監聽感應器的變化,當值有變化的時候會調用onSensorChanged方法,具體運行後,用手遮擋耳機附近的感應器,顯示如下:

從上可見光照的效果很明顯了。接著我們來試下加速度感應器。這裡實現搖一搖功能,並且成功了震動。

修改布局如下:

<!--{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: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="搖一搖擷取更多哦!" 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></textview></linearlayout>

接著添加代碼如下:
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 {    private 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.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);        vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);    }    private SensorEventListener 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("恭喜你搖一搖成功,新年快樂!");            } else {                //Toast.makeText(getApplicationContext(), "請使勁搖哦!", Toast.LENGTH_SHORT).show();            }        }        @Override        public void onAccuracyChanged(Sensor sensor, int i) {        }    };}

這裡的代碼和LightSensor的代碼差不多,主要是當三個方向的加速度大於19的時候就表示在搖動了,然後震動下手機就ok了。效果如下:

最後來學習下magneticSensor了。這裡實現個compass。首先就是提供一張圖片了,修改布局如下:

<!--{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>

接著就是修改MagneticSensor的代碼了:

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.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);        Sensor acclerSensor = sensorManager.getDefaultSensor(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 lastRotateDegree;        @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];            //調用getRotaionMatrix獲得變換矩陣R[]              SensorManager.getRotationMatrix(R, null, acclerValues, magneticValues);            SensorManager.getOrientation(R, values);            //經過SensorManager.getOrientation(R, values);得到的values值為弧度            //轉換為角度            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) {        }    };}

這裡通過加速度和磁感應器來實現一個方向,因為方向感應器官方已經不提倡使用了。運行效果如下:

感應器就先學習這些了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.