我需要添加一个震动功能来刷新我的Android应用程序.

我找到的所有文档都涉及实现SensorListener,但Eclipse告诉我它已弃用,建议使用SensorEventListener.

有没有人对我如何创作这本100有很好的指导?

推荐答案

下面是一个示例代码.

  /* put this into your activity class */
  private SensorManager mSensorManager;
  private float mAccel; // acceleration apart from gravity
  private float mAccelCurrent; // current acceleration including gravity
  private float mAccelLast; // last acceleration including gravity

  private final SensorEventListener mSensorListener = new SensorEventListener() {

    public void onSensorChanged(SensorEvent se) {
      float x = se.values[0];
      float y = se.values[1];
      float z = se.values[2];
      mAccelLast = mAccelCurrent;
      mAccelCurrent = (float) Math.sqrt((double) (x*x + y*y + z*z));
      float delta = mAccelCurrent - mAccelLast;
      mAccel = mAccel * 0.9f + delta; // perform low-cut filter
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }
  };

  @Override
  protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    mSensorManager.unregisterListener(mSensorListener);
    super.onPause();
  }

并将其添加到onCreate方法中:

    /* do this in onCreate */
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mSensorManager.registerListener(mSensorListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
    mAccel = 0.00f;
    mAccelCurrent = SensorManager.GRAVITY_EARTH;
    mAccelLast = SensorManager.GRAVITY_EARTH;

You can then ask "mAccel" wherever you want in your application for the current acceleration, independent from the axis and cleaned from static acceleration such as gravity. It will be approx. 0 if there is no movement, and, lets say >2 if the device is shaked.

根据 comments -要测试这一点,请执行以下操作:

if (mAccel > 12) {
    Toast toast = Toast.makeText(getApplicationContext(), "Device has shaken.", Toast.LENGTH_LONG);
    toast.show();
}

笔记:

为了节省资源(CPU、电池),加速度计应在onPauseonResume之间停用.

Android相关问答推荐

打开平板电脑的下载文件夹中的文件,例如使用其mimeType将Intent发送到我们的应用程序

如何禁用Android 34+版的TileService,但保留以前的版本?

Kotlin DSL:为什么我可以从Play Store获取发布版本的日志(log)?

对支持哪些数据存储区方法感到困惑

无法将Kotlin序列化添加到Android项目

在Jetpack Compose中实现自动换行

LaunchedEffect没有延迟时应用程序崩溃

可以';t将数据插入房间数据库

将输出写入已发布的 Android 应用程序中的日志(log)文件?

参数化类RecyclerView.Adapter的原始使用

retrofit2.HttpException: HTTP 401

Android Jetpack Compose 电视焦点恢复

未找到 com.android.tools.build:gradle:7.4.0 的匹配变体

React-native 3D对象渲染

Jetpack Compose Canvas drawText colored颜色 混合?

在 Jetpack Compose 中使用 .observeAsState() 时,如何在更改 MutableLiveData 的值后开始执行一段代码?

无法通过 retrofit 解析对 kotlin 数据类的 xml 响应

如何从日期 Select 器计算年龄?

从expose 的 dropdownMenu 可组合、jetpack 组合中 Select 选项时,不会触发文本字段的 onValueChange

使用 Jetpack Compose 的深层链接导航到可组合项