Android摇一摇振动效果Demo

时间:2022-11-24 18:36:14

前言

    在微信刚流行的时候,在摇一摇还能用来那啥的时候,我也曾深更半夜的拿着手机晃一晃。当时想的最多的就是。我靠,为神马摇一下须要用这么大的力度,当时我想可能腾讯认为那是个人性的设计。后来才发觉尼马重力加速度设得太高了吧。扯多了。近期项目里须要解决一个振动的问题,因此在学习振动实现的过程中,写了个demo实现了摇一摇振动的效果,这里记录一下。

原理

    摇一摇功能的基本原理就是:利用手机的加速度传感器,当加速度到达某个值时。触发某个事件,比如手机振动、UI改变等。这里要实现该功能,首先须要了解一下Android传感器的使用。

Android传感器Sensor使用

    Android中有多种传感器。眼下Android SDK支持的传感器包含:加速度传感器、光线传感器、陀螺仪传感器、重力传感器、方向传感器、磁场传感器、压力传感器等。可是并非全部手机都具有这些传感器的,由于传感器须要money,因此便宜的手机会选择经常使用的传感器来加入,并且一些高端机型则基本上具有大多数传感器。

Sensor使用步骤

    Android传感器的使用步骤大致可分为三步:
1. 获取传感器管理服对象 SensorManager。
2. 创建传感器事件监听类,该类必须实现android.hardware.SensorEventListener接口。
3. 使用SensorManager.registerListener方法注冊指定的传感器。

传感器事件接口

    SensorEventListener接口。该接口的onSensorChanged()和onAccuracyChanged()方法用于处理对应的传感器事件。
public interface SensorEventListener {

    /**
* Called when sensor values have changed.
* <p>See {@link android.hardware.SensorManager SensorManager}
* for details on possible sensor types.
* <p>See also {@link android.hardware.SensorEvent SensorEvent}.
*
* <p><b>NOTE:</b> The application doesn't own the
* {@link android.hardware.SensorEvent event}
* object passed as a parameter and therefore cannot hold on to it.
* The object may be part of an internal pool and may be reused by
* the framework.
*
* @param event the {@link android.hardware.SensorEvent SensorEvent}.
*/
public void onSensorChanged(SensorEvent event); /**
* Called when the accuracy of a sensor has changed.
* <p>See {@link android.hardware.SensorManager SensorManager}
* for details.
*
* @param accuracy The new accuracy of this sensor
*/
public void onAccuracyChanged(Sensor sensor, int accuracy);
}

Android振动实现

    Android振动效果实现主要是依靠Vibrator服务,详细调用方法例如以下代码所看到的:
import android.app.Activity;
import android.app.Service;
import android.os.Vibrator; public class VibratorHelper {
public static void Vibrate(final Activity activity, long milliseconds) {
Vibrator vibrator = (Vibrator) activity
.getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(milliseconds);
} public static void Vibrate(final Activity activity, long[] pattern,
boolean isRepeat) {
Vibrator vibrator = (Vibrator) activity
.getSystemService(Service.VIBRATOR_SERVICE);
vibrator.vibrate(pattern, isRepeat ? 1 : -1);
}
}

同一时候,还须要在AndroidManifest.xml里添加振动权限:

    <uses-permission android:name="android.permission.VIBRATE"/>

解释一下Vibrate方法的參数:

1. long milliseconds:振动的时长,单位是毫秒。
2. long[] pattern:自己定义振动模式。数组中数字的含义依次是[精巧时长, 振动时长, 精巧时长, 振动时长, ......]。振动时长的单位是毫秒。
3. repeat:是否反复振动,1为反复,-1为仅仅振动一次。

摇一摇振动Demo实现

    好了。了解了摇一摇须要借助加速度传感器。振动须要借助Vibrator服务,那就直接来写代码了。MainActivity类实现例如以下:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast; public class MainActivity extends Activity {
private SensorManager sensorManager;
private SensorEventListener shakeListener;
private AlertDialog.Builder dialogBuilder; private boolean isRefresh = false; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
shakeListener = new ShakeSensorListener(); dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setPositiveButton("确定", new OnClickListener() { @Override
public void onClick(DialogInterface dialog, int which) {
isRefresh = false;
dialog.cancel();
}
}).setMessage("摇到了一个美丽妹子!").create();
} @Override
protected void onResume() {
sensorManager.registerListener(shakeListener,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
super.onResume();
} @Override
protected void onPause() {
// acitivity后台时取消监听
sensorManager.unregisterListener(shakeListener); super.onPause();
} private class ShakeSensorListener implements SensorEventListener {
private static final int ACCELERATE_VALUE = 20; @Override
public void onSensorChanged(SensorEvent event) { // Log.e("zhengyi.wzy", "type is :" + event.sensor.getType()); // 推断是否处于刷新状态(比如微信中的查找附近人)
if (isRefresh) {
return;
} float[] values = event.values; /**
* 一般在这三个方向的重力加速度达到20就达到了摇晃手机的状态 x : x轴方向的重力加速度,向右为正 y :
* y轴方向的重力加速度,向前为正 z : z轴方向的重力加速度。向上为正
*/
float x = Math.abs(values[0]);
float y = Math.abs(values[1]);
float z = Math.abs(values[2]); Log.e("zhengyi.wzy", "x is :" + x + " y is :" + y + " z is :" + z); if (x >= ACCELERATE_VALUE || y >= ACCELERATE_VALUE
|| z >= ACCELERATE_VALUE) {
Toast.makeText(
MainActivity.this,
"accelerate speed :"
+ (x >= ACCELERATE_VALUE ? x
: y >= ACCELERATE_VALUE ? y : z),
Toast.LENGTH_SHORT).show(); VibratorHelper.Vibrate(MainActivity.this, 300);
isRefresh = true;
dialogBuilder.show();
} } @Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
} } }

    效果图:
Android摇一摇振动效果Demo

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd3p5XzE5ODg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">