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) {
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("请开始摇");
}
});
}
}android传感器;摇一摇抽签功能,布布扣,bubuko.com
android传感器;摇一摇抽签功能
原文:http://blog.csdn.net/needkane/article/details/26575185