public class MainActivity extends Activity {
private TextView tv_start;
private TextView tv_temp;
public static int RING_VALUE = 40;//三维xyz三个值总和达到这个值表示摇晃
boolean flag = false; //表示是否在播放音乐
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_start = (TextView) findViewById(R.id.tv_start);
tv_temp = (TextView) findViewById(R.id.tv_temp);
//获取系统传感器管理器
SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//获取指定的一个传感器(加速度传感器)
Sensor accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//注册传感器的监听器
sm.registerListener(new SensorEventListener()
{
@Override
public void onSensorChanged(SensorEvent arg0)
{
//传感器数据变化,在该方法中我们可以获取传感器变化的值
float x = arg0.values[0];
float y = arg0.values[1];
float z = arg0.values[2];
if ((Math.abs(x)+Math.abs(y)+Math.abs(z)) >=
RING_VALUE && flag == false) {
//是否正在播放音乐的标志
flag = true;
//播放音乐界面
tv_start.setVisibility(View.VISIBLE);
//播放音乐的
MediaPlayer player = MediaPlayer.create(MainActivity.this,
R.raw.houge);
//开始播放音乐
player.start();
//监听该首歌有没有播放完
player.setOnCompletionListener(new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer arg0) {
arg0.release();
flag = false;
tv_start.setVisibility(View.GONE);
}
});
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int
i) {
//传感器精度的变化
}
}, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
//获取温度传感器
Sensor temperature = sm.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
sm.registerListener(new SensorEventListener()
{
@Override
public void onSensorChanged(SensorEvent arg0)
{
float temp = arg0.values[0];
temp = (float) (Math.round(temp *10.0)/10.0);
tv_temp.setText("温度:"+temp+"°C");
}
@Override
public void onAccuracyChanged(Sensor arg0, int
arg1) {
}
}, temperature, SensorManager.SENSOR_DELAY_NORMAL);
}
} |