Android gravity sensing.

Source: Internet
Author: User

I. What is a sensor:

Sensors can detect functions such as light, heat, temperature, gravity, and direction!

Ii. Which sensors are provided in Android:

1. Acceleration Sensor (gravity sensor)

2. gyroscope Sensor

3. Optical Sensors

5. Constant Magnetic Field Sensor

6. Direction Sensor

7. Constant Pressure Sensors

8. Proximity sensor

9. Temperature Sensor

Today, we will introduce the most common and frequently used sensor in game development,Acceleration Sensor (gravity sensor )!


Because the simulator cannot be tested, I used my mobile phone to debug it ~, First two;


 

··· · 50 ······· · 90 ····· · 140 · 150
  1. /**
  2. * @ Author himi
  3. * @ Sensor acceleration sensor, also known as gravity Sensor
  4. * @ SDK 1.5 (API 3) supports sensors.
  5. * @ Explanation: This sensor not only detects the player's mobile phone reversal action, but also gets different sensor values based on the extent to which the mobile phone is reversed!
  6. */
  7. Public class mysurfaceview extends surfaceview implements callback, runnable {
  8. Private thread th = new thread (this );
  9. Private surfaceholder SFH;
  10. Private canvas;
  11. Private paint;
  12. Private sensormanager Sm;
  13. Private sensor;
  14. Private sensoreventlistener mysensorlistener;
  15. Private int arc_x, arc_y; // The position of x and y in the circle
  16. Private float x = 0, y = 0, Z = 0;
  17. Public mysurfaceview (context ){
  18. Super (context );
  19. This. setkeepscreenon (true );
  20. SFH = This. getholder ();
  21. SFH. addcallback (this );
  22. Paint = new paint ();
  23. Paint. setantialias (true );
  24. Setfocusable (true );
  25. Setfocusableintouchmode (true );
  26. // Get the sensor management object through the service
  27. Sm = (sensormanager) mainactivity. Ma. getsystemservice (service. sensor_service );
  28. Sensor = Sm. getdefasensensor (sensor. type_accelerometer); // obtain a gravity sensor instance.
  29. // Type of the type_accelerometer accelerometer (gravity sensor.
  30. // Type_all describes all types of sensors.
  31. // Type_gyroscope gyroscope sensor type
  32. // Type_light Optical Sensor Type
  33. // Type_magnetic_field constant magnetic field sensor type.
  34. // Type of the sensor in the type_orientation direction.
  35. // Type_pressure describes a constant pressure sensor type
  36. // Type_proximity constant description close sensor
  37. // Type_temperature temperature sensor type description
  38. Mysensorlistener = new sensoreventlistener (){
  39. @ Override
  40. // Response to this function when the value obtained by the sensor changes
  41. Public void onsensorchanged (sensorevent event) {// Note 1
  42. // The value obtained by the sensor is changed and processed here
  43. X = event. Values [0]; // tumble horizontally on the mobile phone
  44. // X> 0 indicates that the current mobile phone is flipped left x <0 indicates that the mobile phone is flipped right.
  45. Y = event. Values [1]; // scroll down the phone vertically
  46. // Y> 0 indicates that the current mobile phone is flipped down. Y <0 indicates that the current mobile phone is flipped down.
  47. Z = event. Values [2]; // screen orientation
  48. // Z> 0 mobile phone screen up Z <0 mobile phone screen down
  49. Arc_x-= x; // Note 2
  50. Arc_y + = y;
  51. }
  52. @ Override
  53. // Response to this function when the sensor's precision changes
  54. Public void onaccuracychanged (sensor, int accuracy ){
  55. // Todo auto-generated method stub
  56. }
  57. };
  58. SM. registerlistener (mysensorlistener, sensor, sensormanager. sensor_delay_game );
  59. // The first parameter is the sensor listener, and the second parameter is the sensor instance to be monitored.
  60. // The last parameter is the sensor speed type of the listener. There are four formats in total.
  61. // Sensor_delay_normal
  62. // Sensor_delay_ui
  63. // Sensor_delay_game is suitable for games (we must select this option ~)
  64. // Sensor_delay_fastest is the fastest
  65. }
  66. Public void surfacecreated (surfaceholder holder ){
  67. Arc_x = This. getwidth ()/2-25;
  68. Arc_y = This. getheight ()/2-25;
  69. Th. Start ();
  70. }
  71. Public void draw (){
  72. Try {
  73. Canvas = SFH. lockcanvas ();
  74. If (canvas! = NULL ){
  75. Canvas. drawcolor (color. Black );
  76. Paint. setcolor (color. Red );
  77. Canvas. drawarc (New rectf (arc_x, arc_y, arc_x + 50,
  78. Arc_y + 50), 0,360, true, paint );
  79. Paint. setcolor (color. Yellow );
  80. Canvas. drawtext ("Current gravity sensor value:", arc_x-50, arc_y-30, paint );
  81. Canvas. drawtext ("x =" + x + ", y =" + Y + ", Z =" + Z,
  82. Arc_x-50, arc_y, paint );
  83. String temp_str = "himi prompt :";
  84. String temp_str2 = "";
  85. String temp_str3 = "";
  86. If (x <1 & x>-1 & Y <1 & Y>-1 ){
  87. Temp_str + = "the current mobile phone is placed horizontally ";
  88. If (z> 0 ){
  89. Temp_str2 + = "and screen up ";
  90. } Else {
  91. Temp_str2 + = "and the screen is down, prompting you not to lie down and play with your phone. It's not good for your eyes ~ ";
  92. }
  93. } Else {
  94. If (x> 1 ){
  95. Temp_str2 + = "the current mobile phone is in the Left flip status ";
  96. } Else if (x <-1 ){
  97. Temp_str2 + = "the current mobile phone is in the right turn state ";
  98. }
  99. If (Y> 1 ){
  100. Temp_str2 + = "the current mobile phone is turning down ";
  101. } Else if (Y <-1 ){
  102. Temp_str2 + = "the current mobile phone is turning up ";
  103. }
  104. If (z> 0 ){
  105. Temp_str3 + = "and screen up ";
  106. } Else {
  107. Temp_str3 + = "and the screen is down, prompting you not to lie down and play with your phone. It's not good for your eyes ~ ";
  108. }
  109. }
  110. Paint. settextsize (20 );
  111. Canvas. drawtext (temp_str, 0, 50, paint );
  112. Canvas. drawtext (temp_str2, 0, 80, paint );
  113. Canvas. drawtext (temp_str3, 0,110, paint );
  114. }
  115. } Catch (exception e ){
  116. Log. V ("himi", "Draw is error! ");
  117. } Finally {
  118. SFH. unlockcanvasandpost (canvas );
  119. }
  120. }
  121. @ Override
  122. Public void run (){
  123. // Todo auto-generated method stub
  124. While (true ){
  125. Draw ();
  126. Try {
  127. Thread. Sleep (100 );
  128. } Catch (exception ex ){
  129. }
  130. }
  131. }
  132. Public void surfacechanged (surfaceholder holder, int format, int width, int height ){
  133. }
  134. Public void surfacedestroyed (surfaceholder holder ){
  135. }
  136. }

 

Note 1:

The onsensorchanged event of sensoreventlistener will return the sensorevent object, which contains the latest sensor data, and obtain a float [] array through event. values! For different sensor types, the array contains different numbers of elements. The gravity sensor always returns an array with a length of 3, representing the values in the X, Y, and Z directions, respectively. The Z axis indicates whether the screen is facing up or down;

 

Note that the current mobile phone is still in the vertical or horizontal direction, because this will affect the meaning of X and Y!

If the current mobile phone is a portrait screen:

X> 0 indicates that the current mobile phone is flipped left. x <0 indicates that the mobile phone is flipped right.

Y> 0 indicates that the current mobile phone is flipped down. Y <0 indicates that the current mobile phone is flipped down.

If the current mobile phone is a horizontal screen:

X> 0 indicates that the current mobile phone is flipped down x <0

Y> 0 indicates that the current mobile phone is flipped right Y <0 Left flip

 

I would like to remind you that:

1. Consider the player's current mobile phone posture, such as portrait screen and landscape screen.

2. Depending on the screen, although the screen coordinate system will automatically change, the sensor value will not automatically change the coordinate system! So why do the values we retrieve from the sensor indicate different actions when the screen is changed !!! Therefore, during game development, when people perform operations such as character movement and image movement, the positive and negative values of gesture X and Y must be clear! Otherwise, the player will play and vomit (too dizzy !) --,

 

NOTE 2:

This should have been arc_x + = x; but because my screen is portrait now! The gesture that causes x> 0 indicates that the player has turned the mobile phone to the left, but the circle on our screen should move according to the reverse of the person. Here, the player turns the mobile phone to the left, we should reduce the X coordinate of the prototype! So here we write arc_x-= x ;!

 

To sum up, although this chapter only describes a gravity sensor, it is sufficient because if you want to use another sensor, you only need to perform the following steps:

1. Use sensormanager. getdefasensensor (); input a parameter of the sensor you want to get its instance!

2. register!

3. Process events in the listener!

OK! It's so simple,

Source code:Http://download.csdn.net/source/2985714

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.