There are several types of sensors:
Direction Sensor: Sensor. TYPE_ORIENTATION
Acceleration (gravity) Sensor: Sensor. TYPE_ACCELEROMETER
Light Sensor: Sensor. TYPE_LIGHT
Magnetic Field Sensor: Sensor. TYPE_MAGNETIC_FIELD
Distance (proximity) Sensor: Sensor. TYPE_PROXIMITY
Temperature Sensor: Sensor. TYPE_TEMPERATURE
Here we use the acceleration sensor.
Package com. jamin. sensor;
Import android. app. Activity;
Import android. app. Service;
Import android. hardware. Sensor;
Import android. hardware. SensorEvent;
Import android. hardware. SensorEventListener;
Import android. hardware. SensorManager;
Import android. OS. Bundle;
Import android. OS. Vibrator;
Import android. util. Log;
Import android. view. View;
Import android. widget. Button;
Import android. widget. TextView;
Public class SensorTestActivity extends Activity implements SensorEventListener {
/** Called when the activity is first created .*/
TextView TV = null;
Button button = null;
SensorManager sensorManager = null;
Vibrator vibrator = null;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button = (Button) findViewById (R. id. button1 );
TV = (TextView) findViewById (R. id. textview1 );
Button. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
TV. setText ("text restoration ");
}
});
SensorManager = (SensorManager) getSystemService (SENSOR_SERVICE );
Vibrator = (Vibrator) getSystemService (Service. VIBRATOR_SERVICE );
}
@ Override
Protected void onPause (){
// TODO Auto-generated method stub
Super. onPause ();
SensorManager. unregisterListener (this );
}
@ Override
Protected void onResume (){
// TODO Auto-generated method stub
Super. onResume ();
SensorManager. registerListener (this, sensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER), SensorManager. SENSOR_DELAY_NORMAL );
}
@ Override
Public void onAccuracyChanged (Sensor sensor, int accuracy ){
// Call back this method when the sensor precision changes. Do nothing.
}
@ Override
Public void onSensorChanged (SensorEvent event ){
Int sensorType = event. sensor. getType ();
// Values [0]: X axis, values [1]: Y axis, values [2]: Z axis
Float [] values = event. values;
If (sensorType = Sensor. TYPE_ACCELEROMETER ){
If (Math. abs (values [0])> 17 | Math. abs (values [1])> 17 | Math. abs (values [2])> 17 )){
Log. d ("sensor", "============= values [0] =" + values [0]);
Log. d ("sensor", "============== values [1] =" + values [1]);
Log. d ("sensor", "============= values [2] =" + values [2]);
TV. setText ("Shake ");
// Shake the phone, and then follow the vibration prompt ~~
Vibrator. vibrate (500 );
}
}
}
}
Remember to switch the sensor listening event during onresume and onpause.
If you want to adjust the sensitivity of the sensor, modify it. The value [0, 1, 2] is greater than the upper limit.
From jamin0107