最近许多程序都使用了Android机硬件的传感器(Sensor),其中传感器又分为好几种,比如方向,加速计,温度,磁场等,但是不同机型并不保证包括所有类型的传感器。不过大部分机子都包括加速计,下面写一个简单的demo来演示利用加速计改变应用背景颜色。
1.Activity:
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private long lastUpdate;
private View view;
private static final int[] colors = { Color.RED, Color.BLACK, Color.BLUE,
Color.CYAN, Color.YELLOW, Color.GRAY, Color.GREEN };
private Random r = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = findViewById(R.id.parent);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// x轴,y轴,z轴加速度
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) {
if (actualTime - lastUpdate < 500) {
return;
}
lastUpdate = actualTime;
Toast.makeText(this, "设备甩了一下", Toast.LENGTH_SHORT).show();
view.setBackgroundColor(colors[r.nextInt(colors.length)]);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
protected void onResume() {
super.onResume();
// 注册监听器
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
// 注销监听器
sensorManager.unregisterListener(this);
}
}
2. layout文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</LinearLayout>
3. 使用传感器不需要在清单文件中添加权限。
4.甩几下手机:
... Hope it helps you.