package com.bwie.a1511kday5sensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView textView;
private SensorManager sensorManager;
private List<Sensor> sensors;
private int[] musics = {R.raw.music1,R.raw.music2,R.raw.music3,R.raw.music4};
int index = 0;
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//播放音乐
mp = MediaPlayer.create(this, musics[index]);
mp.start();
btn = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
//得到传感器管理器
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//获得加速度传感器,测试
Sensor sensor1 = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//添加传感器的监听
sensorManager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
//获得xyz三轴的值的改变,显示在屏幕中
StringBuffer sb = new StringBuffer();
sb.append("x:");
sb.append(event.values[0]);
sb.append("\n\t");
sb.append("y:");
sb.append(event.values[1]);
sb.append("\n\t");
sb.append("z:");
sb.append(event.values[2]);
sb.append("\n\t");
textView.setText(sb.toString());
Log.i("main",sb.toString());
//甩歌功能
if(event.values[2] > 12){//z轴的变化大于12,表示刻意的甩动
mp.stop();
mp.release();
index++;
index = index%musics.length;
mp = MediaPlayer.create(MainActivity.this,musics[index]);
mp.start();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
},sensor1,SensorManager.SENSOR_DELAY_UI);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获得本机的传感器
sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
StringBuffer sb = new StringBuffer();
//遍历,得到所有传感器
for(int i=0;i<sensors.size();i++){
Sensor sensor = sensors.get(i);
sb.append(sensor.getName()+"\n\t");
}
textView.setText(sb.toString());
}
});
}
}