package com.kane.sensortest;
import java.util.Random;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView content;
private Button btn;
//抽簽
private String[] allResults={"她愛我","她不愛我","她愛他"};
private Random random=new Random();
private boolean flag=false;
private long startTime = -1;
//初始水平方向的x加速度
private float max = 0;
private float min = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content=(TextView) findViewById(R.id.content);
btn=(Button) findViewById(R.id.btn);
//調用傳感器服務
SensorManager manager=(SensorManager) getSystemService(SENSOR_SERVICE);
//建立傳感器對象
Sensor s=manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);//加速器對象,還有其他很多對象
// 設置監聽,當傳感器中的值有變化時,自動進行監聽反饋
manager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (flag) {
if (startTime==-1) {
startTime=System.currentTimeMillis();
}
//當有變化時,自動執行此方法
//通過event可以取得三個方向的加速度值
float[] values=event.values;
/*StringBuilder builder=new StringBuilder();
builder.append(values[0]+"\r\n");
builder.append(values[1]+"\r\n");
builder.append(values[2]+"\r\n");
content.setText(builder);*/
if(values[0]>max){
max=values[0];
}
if (values[0]
min=values[0];
}
if (max > 10 && min < -10) {
flag = false;
long x=System.currentTimeMillis();
if(x-startTime>2000){
Toast.makeText(MainActivity.this, "超時,請重新搖",
Toast.LENGTH_SHORT).show();
}
else {
//可以出結果了
//隨機生成
int index=random.nextInt(3);
content.setText("結果:"+allResults[index]);
}
startTime = -1;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, s, 0);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
flag=true;
content.setText("請開始搖");
}
});
}
}