1 import android.app.Activity; 2 import android.content.Context; 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 9 public class MainActivity extends Activity implements SensorEventListener { 10 11 private SensorManager mSensorManager; 12 private Sensor mProximity; 13 14 @Override 15 public final void onCreate(Bundle savedInstanceState) { 16 super.onCreate(savedInstanceState); 17 setContentView(R.layout.main); 18 19 // Get an instance of the sensor service, and use that to get an instance of 20 // a particular sensor. 21 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 22 mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); 23 } 24 25 @Override 26 public final void onAccuracyChanged(Sensor sensor, int accuracy) { 27 // Do something here if sensor accuracy changes. 28 } 29 30 @Override 31 public final void onSensorChanged(SensorEvent event) { 32 float distance = event.values[0]; 33 System.out.println("distance--->" + distance); 34 System.out.println(mProximity.getMaximumRange()); 35 // Do something with this sensor data. 36 } 37 38 @Override 39 protected void onResume() { 40 // Register a listener for the sensor. 41 super.onResume(); 42 mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL); 43 } 44 45 @Override 46 protected void onPause() { 47 // Be sure to unregister the sensor when the activity pauses. 48 super.onPause(); 49 mSensorManager.unregisterListener(this); 50 } 51 52 53 }
时间: 2024-10-12 20:52:16