在Android 1.5上处理震动事件

【在Android 1.5上处理震动事件】知是行的主意,行是知的功夫。这篇文章主要讲述在Android 1.5上处理震动事件相关的知识,希望能为你提供帮助。

  1. package com.gedankentank.android.sensor;
  2.  
  3. import java.util.List;
  4.  
  5. import android.hardware.Sensor;
  6. import android.hardware.SensorEvent;
  7. import android.hardware.SensorEventListener;
  8. import android.hardware.SensorManager;
  9. import android.util.Log;
  10.  
  11. public class AccelerometerListener implements SensorEventListener {
  12.  
  13. private SensorManager sensorManager;
  14. private List< Sensor> sensors;
  15. private Sensor sensor;
  16. private long lastUpdate = -1;
  17. private long currentTime = -1;
  18.  
  19. private float last_x, last_y, last_z;
  20. private float current_x, current_y, current_z, currenForce;
  21. private static final int FORCE_THRESHOLD = 900;
  22. private final int DATA_X = SensorManager.DATA_X;
  23. private final int DATA_Y = SensorManager.DATA_Y;
  24. private final int DATA_Z = SensorManager.DATA_Z;
  25.  
  26. public AccelerometerListener( Activity parent) {
  27. SensorManager sensorService = ( SensorManager) parent.getSystemService( Context.SENSOR_SERVICE) ;
  28. this.sensorManager = sensorManager;
  29. this.subscriber = subscriber;
  30. this.sensors = sensorManager.getSensorList( Sensor.TYPE_ACCELEROMETER) ;
  31. if ( sensors.size( ) > 0) {
  32. sensor = sensors.get( 0) ;
  33. }
  34. }
  35. public void start ( ) {
  36. if ( sensor!=null) {
  37. sensorManager.registerListener( this, sensor, SensorManager.SENSOR_DELAY_GAME) ;
  38. }
  39. }
  40.  
  41. public void stop ( ) {
  42. sensorManager.unregisterListener( this) ;
  43. }
  44.  
  45. public void onAccuracyChanged( Sensor s, int valu) {
  46.  
  47.  
  48. }
  49. public void onSensorChanged( SensorEvent event) {
  50.  
  51. if ( event.sensor.getType( ) != Sensor.TYPE_ACCELEROMETER || event.values.length < 3)
  52. return;
  53.  
  54. currentTime = System.currentTimeMillis( ) ;
  55.  
  56. if ( ( currentTime - lastUpdate) > 100) {
  57. long diffTime = ( currentTime - lastUpdate) ;
  58. lastUpdate = currentTime;
  59.  
  60. current_x = event.values[ DATA_X] ;
  61. current_y = event.values[ DATA_Y] ;
  62. current_z = event.values[ DATA_Z] ;
  63.  
  64. currenForce = Math.abs( current_x+current_y+current_z - last_x - last_y - last_z) / diffTime * 10000;
  65.  
  66. if ( currenForce > FORCE_THRESHOLD) {
  67.  
  68. // Device has been shaken now go on and do something
  69. // you could now inform the parent activity ...
  70.  
  71. }
  72. last_x = current_x;
  73. last_y = current_y;
  74. last_z = current_z;
  75.  
  76. }
  77. }
  78.  
  79. }


    推荐阅读