标签:android blog io os ar java div 2014 art
package com.beyond.phonestolen; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.app.Activity; import android.widget.Toast; public class MainActivity extends Activity { //传感器管理器 private SensorManager sm; //距离传感器 private Sensor sensor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //1,通过获取系统服务,得到传感器管理器 sm=(SensorManager) getSystemService(SENSOR_SERVICE); //2,通过传感器管理器获取指定的距离传感器 sensor=sm.getDefaultSensor(Sensor.TYPE_PROXIMITY); //3,通过传感器管理器注冊监听器,监听距离传感器的感应事件 sm.registerListener(new MyListener(), sensor, SensorManager.SENSOR_DELAY_GAME); } private class MyListener implements SensorEventListener{ @Override public void onSensorChanged(SensorEvent event) { float distance=event.values[0]; //System.out.println(val[0]); Toast.makeText(MainActivity.this, ""+distance, 0).show(); //当手机在裤袋里面时,距离为0 if (distance<1.0f) { return; } //当手机脱离裤袋的时候,距离为1,播放音乐 playMusic(); } private void playMusic() { // 播放音乐 MediaPlayer mPlayer=MediaPlayer.create(MainActivity.this, R.drawable.alarm); mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mPlayer.prepare(); } catch (Exception e) { e.printStackTrace(); } //理论上应该异步准备,在准备完毕的回调函数中启动播放器 mPlayer.start(); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } }
标签:android blog io os ar java div 2014 art
原文地址:http://www.cnblogs.com/bhlsheji/p/4025053.html