In this example, the focus is on how to use SensorManager. SENSOR_ACCELEROMETER to determine the device's moving direction: the result is displayed in Log mode rather than in graphics mode, so the arrow displayed in this example is always up.
This example is reasonable in Hardware. The code for how to use SENSOR_ACCELEROMETER to determine the device's moving direction is as follows:
[Java]
Public void onSensorChanged (int sensor, float [] values ){
Boolean show = false;
Float [] diff = new float [3];
For (int I = 0; I <3; I ++ ){
Diff [I] = Math. round (mScale [I]
* (Values [I]-mPrev [I]) * 0.45f );
If (Math. abs (diff [I])> 0 ){
Show = true;
}
MPrev [I] = values [I];
}
...
Long now = android. OS. SystemClock. uptimeMillis ();
If (now-mlastgestoretime> 1000 ){
MLastGestureTime = 0;
Float x = diff [0];
Float y = diff [1];
Boolean gestX = Math. abs (x)> 3;
Boolean gestY = Math. abs (y)> 3;
If (gestX | gestY )&&! (GestX & gestY )){
If (gestX ){
If (x <0 ){
Android. util. Log. e ("test ",
"<LEFT <");
} Else {
Android. util. Log. e ("test ",
">>>>>>>>> RITE >>>>>>>>>> ");
}
} Else {
If (y <-2 ){
Android. util. Log. e ("test ",
"<UP <");
} Else {
Android. util. Log. e ("test ",
">>>>>>>>>>>>>>>>>>>> ");
}
}
MLastGestureTime = now;
}
}
}
Public void onSensorChanged (int sensor, float [] values ){
Boolean show = false;
Float [] diff = new float [3];
For (int I = 0; I <3; I ++ ){
Diff [I] = Math. round (mScale [I]
* (Values [I]-mPrev [I]) * 0.45f );
If (Math. abs (diff [I])> 0 ){
Show = true;
}
MPrev [I] = values [I];
}
...
Long now = android. OS. SystemClock. uptimeMillis ();
If (now-mlastgestoretime> 1000 ){
MLastGestureTime = 0;
Float x = diff [0];
Float y = diff [1];
Boolean gestX = Math. abs (x)> 3;
Boolean gestY = Math. abs (y)> 3;
If (gestX | gestY )&&! (GestX & gestY )){
If (gestX ){
If (x <0 ){
Android. util. Log. e ("test ",
"<LEFT <");
} Else {
Android. util. Log. e ("test ",
">>>>>>>>> RITE >>>>>>>>>> ");
}
} Else {
If (y <-2 ){
Android. util. Log. e ("test ",
"<UP <");
} Else {
Android. util. Log. e ("test ",
">>>>>>>>>>>>>>>>>>>> ");
}
}
MLastGestureTime = now;
}
}
} If you want to move the arrow on the screen as the device moves, refer to the Compass example and add:
[Java]
MValues = values;
If (mView! = Null ){
MView. invalidate ();
}
MValues = values;
If (mView! = Null ){
MView. invalidate ();
}
Author: mapdigit