手机方向和加速度传感器技术

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.package cn.itcast.sensor;

2.

3.import android.app.Activity;

4.import android.hardware.Sensor;

5.import android.hardware.SensorEvent;

6.import android.hardware.SensorEventListener;

7.import android.hardware.SensorManager;

8.import android.os.Bundle;

9.import android.widget.TextView;

10.

11.public class MainActivity extends Activity {

12. private TextView accelerometerView;

13. private TextView orientationView;

14. private SensorManager sensorManager;

15. private MySensorEventListener sensorEventListener;

16. @Override

17. public void onCreate(Bundle savedInstanceState) {

18. super.onCreate(savedInstanceState);

19. setContentView(yout.main);

20.

21. sensorEventListener = new MySensorEventListener();

22. accelerometerView = (TextView) this.findViewById(R.id.a

ccelerometerView);

23. orientationView = (TextView) this.findViewById(R.id.ori

entationView);

24. //获取感应器管理器

25. sensorManager = (SensorManager) getSystemService(SENSOR

_SERVICE);

26. }

27. @Override

28. protected void onResume() {

29. Sensor orientationSensor = sensorManager.getDefaultSens

or(Sensor.TYPE_ORIENTATION);

30. sensorManager.registerListener(sensorEventListener, ori

entationSensor, SensorManager.SENSOR_DELAY_NORMAL);

31.

32. Sensor accelerometerSensor = sensorManager.getDefaultSe

nsor(Sensor.TYPE_ACCELEROMETER);

33. sensorManager.registerListener(sensorEventListener, acc

elerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

34. super.onResume();

35. }

36. private final class MySensorEventListener implements Sensor

EventListener{

37. @Override

38. public void onSensorChanged(SensorEvent event) {//可以

得到传感器实时测量出来的变化值

39. if(event.sensor.getType()==Sensor.TYPE_ORIENTATION)

{

40. float x = event.values[SensorManager.DATA_X];

41. float y = event.values[SensorManager.DATA_Y];

42. float z = event.values[SensorManager.DATA_Z];

43. orientationView.setText("Orientation: " + x + "

, " + y + ", " + z);

44. }else if(event.sensor.getType()==Sensor.TYPE_ACCELE

ROMETER){

45. float x = event.values[SensorManager.DATA_X];

46. float y = event.values[SensorManager.DATA_Y];

47. float z = event.values[SensorManager.DATA_Z];

48. accelerometerView.setText("Accelerometer: " + x

+ ", " + y + ", " + z);

49. }

50.

51. }

52. @Override

53. public void onAccuracyChanged(Sensor sensor, int accura

cy) {

54. }

55. }

56.

57. @Override

58. protected void onPause() {

59. sensorManager.unregisterListener(sensorEventListener);

60. super.onPause();

61. }

62.

63.

64.}

2:

Xml代码

相关文档
最新文档