Android implements the shake function, and android implements the shake function.

Source: Internet
Author: User

Android implements the shake function, and android implements the shake function.

To implement the "Shake" function, it is actually very simple. It is to detect the mobile phone's gravity sensor. The specific implementation code is as follows:

1. Add operation permissions in AndroidManifest. xml

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

II. Implementation Code

[Java]View plaincopy
  1. Package com. xs. test;
  2. Import android. app. Activity;
  3. Import android. hardware. Sensor;
  4. Import android. hardware. SensorEvent;
  5. Import android. hardware. SensorEventListener;
  6. Import android. hardware. SensorManager;
  7. Import android. OS. Bundle;
  8. Import android. OS. Handler;
  9. Import android. OS. Message;
  10. Import android. OS. Vibrator;
  11. Import android. util. Log;
  12. Import android. widget. Toast;
  13. /**
  14. * Android mobile phone monitoring-"Shake"
  15. *
  16. * @ Author single Hongyu
  17. *
  18. */
  19. Public class testsens?ti=extends Activity {
  20. Private SensorManager sensorManager;
  21. Private Vibrator vibrator;
  22. Private static final String TAG = "testsens?ti= ";
  23. Private static final int SENSOR_SHAKE = 10;
  24. /** Called when the activity is first created .*/
  25. @ Override
  26. Public void onCreate (Bundle savedInstanceState ){
  27. Super. onCreate (savedInstanceState );
  28. SetContentView (R. layout. main );
  29. SensorManager = (SensorManager) getSystemService (SENSOR_SERVICE );
  30. Vibrator = (Vibrator) getSystemService (VIBRATOR_SERVICE );
  31. }
  32. @ Override
  33. Protected void onResume (){
  34. Super. onResume ();
  35. If (sensorManager! = Null) {// register the listener
  36. SensorManager. registerListener (sensorEventListener, sensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER), SensorManager. SENSOR_DELAY_NORMAL );
  37. // The first parameter is Listener, the second parameter is the sensor type, and the third parameter value obtains the frequency of sensor information.
  38. }
  39. }
  40. @ Override
  41. Protected void onPause (){
  42. Super. onPause ();
  43. If (sensorManager! = Null) {// cancel the listener
  44. SensorManager. unregisterListener (sensorEventListener );
  45. }
  46. }
  47. /**
  48. * Gravity Sensing Monitoring
  49. */
  50. Private SensorEventListener sensorEventListener = new SensorEventListener (){
  51. @ Override
  52. Public void onSensorChanged (SensorEvent event ){
  53. // Execute this method when the sensor information changes
  54. Float [] values = event. values;
  55. Float x = values [0]; // gravity acceleration in the x axis direction, positive to the right
  56. Float y = values [1]; // acceleration of gravity in the y axis, positive forward
  57. Float z = values [2]; // acceleration of gravity in the z axis, positive upward
  58. Log. I (TAG, "acceleration of gravity in the x axis" + x + "; acceleration of gravity in the y axis" + y + "; acceleration of gravity in the z axis" + z );
  59. // Generally, when the acceleration of gravity in these three directions reaches 40, the mobile phone is shaken.
  60. Int medumValue = 19; // Samsung i9250 cannot shake more than 20, no way, set only 19
  61. If (Math. abs (x)> medumValue | Math. abs (y)> medumValue | Math. abs (z)> medumValue ){
  62. Vibrator. vibrate (200 );
  63. Message msg = new Message ();
  64. Msg. what = SENSOR_SHAKE;
  65. Handler. sendMessage (msg );
  66. }
  67. }
  68. @ Override
  69. Public void onAccuracyChanged (Sensor sensor, int accuracy ){
  70. }
  71. };
  72. /**
  73. * Action execution
  74. */
  75. Handler handler = new Handler (){
  76. @ Override
  77. Public void handleMessage (Message msg ){
  78. Super. handleMessage (msg );
  79. Switch (msg. what ){
  80. Case SENSOR_SHAKE:
  81. Toast. makeText (testsens?ti=. this, "Shake detected and executed! ", Toast. LENGTH_SHORT). show ();
  82. Log. I (TAG, "Shake detected. execute the operation! ");
  83. Break;
  84. }
  85. }
  86. };
  87. }
  88. This kind of shaking is common. Without the enhancement of the algorithm, the acceleration of gravity is 10.
  89. Algorithm Optimization:
  90. 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; // adjust the sensitivity of this value
    Private long lastUpdateTime;
    Private float lastX;
    Private float lastY;
    Private float lati;
    @ 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. getdefasensensor (Sensor. TYPE_ACCELEROMETER );
    }
    If (sensor! = Null ){
    SensorManager. registerListener (sensorEventListener,
    Sensor,
    SensorManager. SENSOR_DELAY_GAME); // select the sensor frequency here.
    }
    }


    /**
    * Gravity Sensing Monitoring
    */
    Private SensorEventListener sensorEventListener = new SensorEventListener (){


    @ Override
    Public void onSensorChanged (SensorEvent event ){
    Long currentUpdateTime = System. currentTimeMillis ();
    Long timeInterval = currentUpdateTime-lastUpdateTime;
    If (timeInterval <UPTATE_INTERVAL_TIME ){
    Return;
    }
    LastUpdateTime = currentUpdateTime;
    // Execute this method when the sensor information changes
    Float [] values = event. values;
    Float x = values [0]; // gravity acceleration in the x axis direction, positive to the right
    Float y = values [1]; // acceleration of gravity in the y axis, positive forward
    Float z = values [2]; // acceleration of gravity in the z axis, positive upward
    Float deltaX = x-lastX;
    Float deltaY = y-lastY;
    Float deltaZ = z-lati;


    LastX = x;
    LastY = y;
    Las-1 = z;
    Double speed = (Math. sqrt (deltaX * deltaX + deltaY * deltaY
    + DeltaZ * deltaZ)/timeInterval) * 100;
    If (speed> = SPEED_SHRESHOLD ){
    Vibrator. vibrate (300 );
    Image. setImageResource (R. drawable. running01 );
    }
    }


    @ Override
    Public void onAccuracyChanged (Sensor sensor, int accuracy ){

    }
    };

    }

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.