Android ApiDemos示例解析(79):Graphics->SensorTest
本例着重点是介绍使用SensorManager.SENSOR_ACCELEROMETER 如何来判断设备的移动方向:使用Log的方式而非图形的方式显示结果,所以运行本例显示的箭头始终向上。
本例归在Hardware比较合理。如何使用SENSOR_ACCELEROMETER判断设备移动方向的代码如下:
[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 - mLastGestureTime > 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",
">>>>>>>>> DOWN >>>>>>>>>>>");
}
}
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 - mLastGestureTime > 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",
">>>>>>>>> DOWN >>>>>>>>>>>");
}
}
mLastGestureTime = now;
}
}
}如果想在设备移动时,屏幕上箭头的指向随着变化,可以参见Compass的例子,加上:
[java]
mValues = values;
if (mView != null) {
mView.invalidate();
}
mValues = values;
if (mView != null) {
mView.invalidate();
}
作者:mapdigit
补充:移动开发 , Android ,