Let's take a look at the simulation of the shaking function, we are based on the mobile phone accelerometer to achieve this function, the implementation of the method is relatively simple.
Mainactivity.java:
Mainactivity.java: Packagecom.location.activity;Importandroid.app.Activity;ImportAndroid.content.Context;ImportAndroid.hardware.Sensor;ImportAndroid.hardware.SensorEvent;ImportAndroid.hardware.SensorEventListener;ImportAndroid.hardware.SensorManager;ImportAndroid.os.Bundle;ImportAndroid.widget.Toast; Public class mainactivity extends Activity { PrivateSensormanager Sensormanager;@Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.main); Sensormanager = (Sensormanager) getsystemservice (Context.sensor_service);//access to servicesSensor sensor = Sensormanager. Getdefaultsensor (Sensor.type_accelerometer);//Sensor Type-acceleration sensorSensormanager.registerlistener (listener, sensor, sensormanager.sensor_delay_normal); }@Override protected void OnDestroy() {if(Sensormanager! =NULL) {Sensormanager.unregisterlistener (listener); }Super. OnDestroy (); }/** * Sensor trigger * / PrivateSensoreventlistener listener =NewSensoreventlistener () { Public void onsensorchanged(Sensorevent event) {floatXValue = Math.Abs (event.values[0]);//X-Axis direction acceleration floatYvalue = Math.Abs (event.values[1]);//Y-Axis direction acceleration floatZvalue = Math.Abs (event.values[2]);//z-axis direction acceleration if(XValue > -|| Yvalue > -|| Zvalue > -) {//has an acceleration value greater than 20 in either direction, which triggers /** * Here we just use toast as an example, you can write various methods in accordance with your own requirements;Toast.maketext (mainactivity. This,"You have activated the Shake function!" ", Toast.length_long). Show (); } } Public void onaccuracychanged(Sensor sensor,intaccuracy) {}};}
Run the following example:
Summary :
1.getSystemService (Context.sensor_service);//Get Sensormanage object;
2.sensormanager.getdefaultsensor (sensor.type_accelerometer);//Get sensor type
3. This article just will shake a shake triggered as toast, there is a need to directly modify the method can be.
Favorite friends pay attention to me Oh! Thanks for your support!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Combat Simple Tutorial-the 31st gun (based on the acceleration sensor's shake-and-shake function example)