传感器之加速传感器
轉載請注明出處:http://blog.csdn.net/mr_leixiansheng/article/details/53692519
功能:搖動手機出現(xiàn)提示
傳感器使用步驟:
1、實例化SensorManager并得到傳感器類型
2、對傳感器實現(xiàn)監(jiān)聽
3、動態(tài)注冊
4、退出時釋放資源(取消注冊)
代碼如下:
package com.example.administrator.accelerometersensor;import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast;public class MainActivity extends AppCompatActivity {private SensorManager sensorManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//設置傳感器類型sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//注冊監(jiān)聽sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);}@Overrideprotected void onDestroy() {super.onDestroy();if (sensorManager != null) {//取消監(jiān)聽釋放資源sensorManager.unregisterListener(listener);}}private SensorEventListener listener = new SensorEventListener() {@Overridepublic void onSensorChanged(SensorEvent sensorEvent) {//獲取x,y,z值float xValue = Math.abs(sensorEvent.values[0]);float yValue = Math.abs(sensorEvent.values[1]);float zValue = Math.abs(sensorEvent.values[2]);//做出響應if (xValue > 15 || yValue > 15 || zValue > 15) {Toast.makeText(MainActivity.this, "搖動了手機", Toast.LENGTH_SHORT).show();}}@Overridepublic void onAccuracyChanged(Sensor sensor, int i) {}}; }總結
- 上一篇: CJJ 61-2017 城市地下管线探测
- 下一篇: HIS系统门急诊医保实时结算接口测试