Android重力感应详情
package com.android.ctbri.SensorTest;
import java.util.Random;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class SensorTest extends Activity {
private SensorManager sensorMgr;
private float x, y, z;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView mTextView = (TextView) findViewById(R.id.textview1);
// start motion detection
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
SensorEventListener lsn = new SensorEventListener() {
public void onSensorChanged(SensorEvent e) {
x = e.values[SensorManager.DATA_X];
y = e.values[SensorManager.DATA_Y];
z = e.values[SensorManager.DATA_Z];
// angle = Math.atan(x / y);
// if (((angle - last_angle) > 0.5)
// || ((angle - last_angle) < -0.5)) {
// Toast.makeText(SensorTest.this, "Love", 1000).show();
Random mRandom = new Random();
int Red = mRandom.nextInt(30);
String str = "" + Red;
if (x > 7 && y > 6 && z < 8) {
Toast.makeText(SensorTest.this, str, 1000).show();
}
mTextView.setText("x=" + (int) x + "," + "y=" + (int) y + ","
+ "z=" + (int) z);
// } else {
// Toast.makeText(SensorTest.this, "i gao ni", 1000).show();
// }
}
public void onAccuracyChanged(Sensor s, int accuracy) {
// ToDo
}
};
// sensorMgr.SENSOR_DELAY_GAME
Sensor sensor = sensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);// .SENSOR_ACCELEROMETER);
sensorMgr
.registerListener(lsn, sensor, SensorManager.SENSOR_DELAY_GAME /* SENSOR_DELAY_GAME */);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
摘自 gongzibai的专栏
补充:移动开发 , Android ,