Objective
in the micro-letter just popular, in shaking a shake can also be used for that what, I had the night of holding a mobile phone dangling flash. At that time thought the most is, I, for God horse shake need to use so much strength, at that time I think maybe Tencent think it is a human nature design, then found that the gravity of the horse is too high. More than that, the recent project needs to solve a vibration problem, so in learning vibration to achieve the process, wrote a demo to achieve a shaking vibration effect, here record.
Principle
the basic principle of shaking the function is to use the mobile acceleration sensor, when the acceleration reaches a certain value, triggering an event, such as phone vibration, UI changes. To implement this feature, you first need to understand the use of the Android sensor.
Android Sensor sensor use
Android has a variety of sensors, the current Android SDK support sensors include: accelerometer, light sensor, gyroscope sensors, gravity sensors, directional sensors, magnetic sensors, pressure sensors and so on. But not all mobile phones have these sensors, because the sensor needs money, so cheap phones will choose the most commonly used sensors to add, and some high-end models are basically the majority of sensors.
Sensor use steps
The steps for using an Android sensor can be broadly divided into three stages:
1. Get sensor Management Service object Sensormanager.
2. Create a sensor event listener class that must implement the Android.hardware.SensorEventListener interface.
3. Use the Sensormanager.registerlistener method to register the specified sensor.
Sensor Event Interface
Sensoreventlistener Interface, the onsensorchanged () and onaccuracychanged () methods of the interface are used to handle the corresponding sensor events.
Public interface Sensoreventlistener {/** * Called when sensor values have.
* <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 ev
ENT} * Object passed as a parameter and therefore cannot hold on to it.
* The object May is part of a internal pool and may is 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 voidOnaccuracychanged (Sensor Sensor, int accuracy);
}
Android Vibration Implementation
the implementation of Android vibration effect is mainly dependent on the vibrator service, the specific invocation method as shown in the following code:
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 VI Brator = (vibrator) activity
. Getsystemservice (service.vibrator_service);
Vibrator.vibrate (milliseconds);
}
public static void vibrate (final activity activity, long[] pattern,
boolean isrepeat) {
Vibrator vibrator = (Vib Rator) Activity
. Getsystemservice (service.vibrator_service);
Vibrator.vibrate (Pattern, isrepeat 1:-1);
}
At the same time, also need to add vibration in the Androidmanifest.xml:
<uses-permission android:name= "Android.permission.VIBRATE"/>
Explain the parameters of the vibrate method:
1. Long milliseconds: the length of the vibration, in milliseconds.
2. long[] Pattern: Custom vibrational mode. The meaning of the numbers in the array is, in turn, [static length, long vibration, long stillness, long vibration, ...]. The unit of vibration length is milliseconds.
3. Repeat: Whether repeated vibration, 1 for repetition,-1 for vibration only once.
Shaking the shaking demo to realize
All right, I got it. Need to use the acceleration sensor, vibration needs the help of vibrator service, then directly to write code. The Mainactivity class is implemented as follows:
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 (OK), new Onclicklistener () {@Override public void OnClick (Dialogin
Terface dialog, int which) {Isrefresh = false;
Dialog.cancel (); }). Setmessage ("to a beautiful sister!")
"). Create (); } @Override protected void Onresume () {Sensormanager.registerlistener (Shakelistener, Sens
Ormanager.getdefaultsensor (Sensor.type_accelerometer), sensormanager.sensor_delay_fastest);
Super.onresume (); @Override protected void OnPause () {//acitivity the background time to cancel the listening Sensormanager.unregisterlistener (sh
Akelistener);
Super.onpause (); Private class Shakesensorlistener implements Sensoreventlistener {private static final int accelerate_v
Alue = 20; @Override public void onsensorchanged (Sensorevent event) {//LOG.E ("Zhengyi.wzy", "TyPE is: "+ event.sensor.getType ());
To determine whether the refresh state (for example, the Finder in a micro-letter) if (Isrefresh) {return;
} float[] values = event.values;
/** * Generally in these three directions of the gravitational acceleration of 20 reached the shaking mobile phone state x:x axis direction of gravity acceleration, right is y: * y axis direction of gravity acceleration, forward z:z axis direction of the acceleration of gravity, positive
* * 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 are:" + y + "Z is:" + z); if (x >= accelerate_value | | y >= accelerate_value | | z >= accelerate_value) {Toast.make Text (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 A
uto-generated method stub}}}
Effect diagram: