最近許多程序都使用了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.
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11