【Android 摇一摇监听实现】卧疾丰暇豫,翰墨时间作。这篇文章主要讲述Android 摇一摇监听实现相关的知识,希望能为你提供帮助。
package com.loaderman.androiddemo; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class ShakeUtils implements SensorEventListener { public ShakeUtils(Context context) { mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); }public void setOnShakeListener(OnShakeListener onShakeListener) { mOnShakeListener = onShakeListener; }public void onResume() { mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); }public void onPause() { mSensorManager.unregisterListener(this); }@Override public void onAccuracyChanged(Sensor sensor, int accuracy) {}@Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); //values[0]:X轴,values[1]:Y轴,values[2]:Z轴 float[] values = event.values; if (sensorType == Sensor.TYPE_ACCELEROMETER) { //这里可以调节摇一摇的灵敏度 if ((Math.abs(values[0]) > SENSOR_VALUE || Math.abs(values[1]) > SENSOR_VALUE || Math.abs(values[2]) > SENSOR_VALUE)) { System.out.println("sensor value =https://www.songbingjia.com/android/=" + " " + values[0] + " " + values[1] + " " + values[2]); if (null != mOnShakeListener) { mOnShakeListener.onShake(); } } } }public interface OnShakeListener { public void onShake(); }private SensorManager mSensorManager = null; private OnShakeListener mOnShakeListener = null; private static final int SENSOR_VALUE = https://www.songbingjia.com/android/14; }
package com.loaderman.androiddemo; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity {ShakeUtils mShakeUtils; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mShakeUtils = new ShakeUtils( this ); mShakeUtils.setOnShakeListener(new ShakeUtils.OnShakeListener() { @Override public void onShake() { System.out.println("摇一摇"); } }); }@Override protected void onResume() { super.onResume(); mShakeUtils.onResume(); } @Override protected void onPause() { super.onPause(); mShakeUtils.onPause( ); } }
推荐阅读
- [Java]基本資料包裝類別 Wrapper Classes
- android studio 环境配置及使用时遇到的问题
- Android架构篇--MVP模式的介绍篇
- Android 动态渐变按钮
- android修改getprop读取到的ro.build.fingerprint属性
- Android 密钥保护和 C/S 网络传输安全理论指南
- Android 2018最新的三方库
- [Angular] Extract Implementation Details of ngrx from an Angular Application with the Facade Pattern
- android recovery代码修改之原生建议