Android to achieve a shake-shake function _android

Source: Internet
Author: User
Tags abs

To achieve the "shake" function, in fact very simple, is to detect the gravity sensor mobile phone, the implementation of the Code as follows:

1, add the Operation permission in the Androidmanifest.xml

2, implementation code

 Package com.xs.test; 
Import android.app.Activity; 
Import Android.hardware.Sensor; 
Import android.hardware.SensorEvent; 
Import Android.hardware.SensorEventListener; 
Import Android.hardware.SensorManager; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.os.Message; 
Import Android.os.Vibrator; 
Import Android.util.Log; 
 
Import Android.widget.Toast; /** * Android mobile Monitor-"Shake" * * @author Tan Hongyu * * * * * * * * * * */public class Testsensoractivity extends activity {private Sens 
  Ormanager Sensormanager; 
 
  Private vibrator Vibrator; 
  private static final String TAG = "testsensoractivity"; 
 
  private static final int sensor_shake = 10; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.main); 
    Sensormanager = (Sensormanager) getsystemservice (Sensor_service); Vibrator = (Vibrator) getsystemservice (Vibrator_service);
  } @Override protected void Onresume () {super.onresume (); if (Sensormanager!= null) {//Registered listener Sensormanager.registerlistener (Sensoreventlistener, Sensormanager.getdefaultse 
      Nsor (Sensor.type_accelerometer), sensormanager.sensor_delay_normal); The first parameter is listener, the second parameter is the resulting sensor type, and the third parameter value gets the frequency of the sensor information} @Override protected void OnPause () {Super.onpau 
    SE (); 
    if (Sensormanager!= null) {//Cancel listener Sensormanager.unregisterlistener (Sensoreventlistener); 
 
    }/** * Gravity induction monitor/private Sensoreventlistener Sensoreventlistener = new Sensoreventlistener () { Executes this method when @Override public void onsensorchanged (Sensorevent event) {//Sensor information changes float[] values = Event.va 
      Lues; float x = values[0]; The acceleration of gravity in the direction of X axis, the right is float y = values[1]; The acceleration of gravity in the direction of the y-axis is the forward float z = values[2]; 
      The gravitational acceleration in the direction of the z axis is positive log.i (TAG, "The gravitational acceleration of the X axis" + x +); The gravitational acceleration of the y-axis direction "+ y +"; The gravitational acceleration of the z-axis "+ z"); Generally in these three directionsThe gravitational acceleration of 40 reached the state of shaking the phone. int medumvalue = 19;//Samsung i9250 No more than 20, no way, just set 19 if (Math.Abs (x) > Medumvalue | | Math.Abs (y) > Medumvalue | | 
        Math.Abs (z) > Medumvalue) {vibrator.vibrate (200); 
        msg = new Message (); 
        Msg.what = Sensor_shake; 
      Handler.sendmessage (msg); 
 
  @Override public void onaccuracychanged (Sensor Sensor, int accuracy) {}}; 
      /** * Action Execution/Handler Handler = new Handler () {@Override public void Handlemessage (msg) { 
      Super.handlemessage (msg); Switch (msg.what) {case SENSOR_SHAKE:Toast.makeText (testsensoractivity.this, "detects shaking, performs operation!") 
        ", Toast.length_short). Show (); LOG.I (TAG, "detect the shaking, perform the operation!") 
        "); 
      Break 
} 
    } 
 
  }; 
 }

This shaking is more common, without the enhancement of the algorithm, the acceleration of gravity is 10.
The algorithm is optimized as follows

Package com.example.url;
Import java.io.IOException;


Import Java.net.URL;


Import Com.hahashijie.imageload.ImageLoader;
Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import android.graphics.drawable.Drawable;
Import Android.hardware.Sensor;
Import android.hardware.SensorEvent;
Import Android.hardware.SensorEventListener;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.os.Vibrator;
Import Android.util.Log;


Import Android.widget.ImageView;  @SuppressLint ("Handlerleak") public class Mainactivity extends activity {private ImageView image; Private Sensormanager
Sensormanager;
Private Sensor Sensor;
Private vibrator Vibrator;
private static final int uptate_interval_time = 50;
private static final int speed_shreshold = 30;//This value regulates the sensitivity of private long lastupdatetime;
private float lastx;
private float lasty; private float Lastz; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Sensormanager = (Sensormanager) getsystemservice (Sensor_service);
Vibrator = (Vibrator) getsystemservice (Vibrator_service);


Image = (ImageView) Findviewbyid (r.id.image); @Override protected void Onresume () {//TODO auto-generated Method Stub super.onresume (); if (Sensormanager null)
    {sensor = Sensormanager.getdefaultsensor (Sensor.type_accelerometer); } if (sensor!= null) {Sensormanager.registerlistener (Sensoreventlistener, sensor, Sensormanager.sensor_delay


_game)//Here Select the Induction Frequency}}/** * Gravity induction monitor/private Sensoreventlistener Sensoreventlistener = new Sensoreventlistener () { @Override public void onsensorchanged (Sensorevent event) {Long currentupdatetime = System.currenttimemillis (); Long Tim
Einterval = Currentupdatetime-lastupdatetime;
if (TimeInterval < uptate_interval_time) {return;} lastupdatetime = Currentupdatetime;
Implement this method when sensor information changes float[] values = event.values; float x = values[0]; The acceleration of gravity in the direction of X axis, the right is float y = values[1]; The acceleration of gravity in the direction of the y-axis is the forward float z = values[2];
The acceleration of gravity in the direction of Z axis is positive float deltax = X-LASTX;
float DeltaY = y-lasty;


float Deltaz = Z-lastz;
LASTX = x;
Lasty = y;
Lastz = Z;
Double speed = (math.sqrt (deltax * deltax + deltay * deltay + Deltaz * Deltaz)/timeinterval) * 100;


if (speed >= speed_shreshold) {vibrator.vibrate; Image.setimageresource (R.DRAWABLE.RUNNING01);}}

@Override public void onaccuracychanged (Sensor Sensor, int accuracy) {}};
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.