Android实现摇一摇功能

jopen 5年前

摇一摇功能主要用到加速度传感器Sensor.TYPE_ACCELEROMETER

摇一摇功能主要是监听手机加速度变化,当超过设定的某一值时,即触发事件

/**   * FileName: MainActivity.java   * @desc 该类是用于显示摇一摇界面   * @author HTP   * @Date    20140311   * @version 1.00    */  public class MainActivity extends Activity implements OnClickListener {   private TabHost tabHost;   private MusicNameDao dao;   // private ImageButton bt_setMusic;   // 声音   private MediaPlayer mediaPlayer;   // 显示摇一摇出现的内容   private TextView tv;   // 要显示在tv中的内容   private String msentence;   // 通过类Sentence可得到摇一摇显示的内容   private Sentence sentence;   // 显示标签“刮一刮”   private TextView tv_rubbler;   // 重力感应管理器   private SensorManager sensorManager;   // 震动控件   private Vibrator vibrator;   // 标签   private static final String TAG = "MainActivity";   private static final int SENSOR_SHAKE = 10;     // private Intent musicIntent = new Intent("com.angel.Android.MUSIC");   /** Called when the activity is first created. */   @Override   public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    dao = new MusicNameDao(this);    Uri musicUri = Uri.parse("android.resource://com.example.romance/raw/"      + dao.getName());      mediaPlayer = MediaPlayer.create(this, musicUri);    //Toast.makeText(MainActivity.this, musicUri.toString(), 1).show();    mediaPlayer.start();// 播放音乐    mediaPlayer.setLooping(true);// 设置循环    dao = new MusicNameDao(this);    // startService(musicIntent);    tv_rubbler = (TextView) findViewById(R.id.tv_rubber);    tv_rubbler.setOnClickListener(this);    // bt_setMusic.setOnClickListener(this);      sentence = new Sentence();    // Uri musicUri = Uri.parse("/sdcard/ttpod/song/虹之间.mp3");    // 获取res/raw/下的音乐路径        tv = (TextView) findViewById(R.id.tv_text);// 关联要显示的TextView空间    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);    vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);   }     @Override   protected void onResume() {    super.onResume();    if (sensorManager != null) {// 注册监听器     sensorManager.registerListener(sensorEventListener,       sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),       SensorManager.SENSOR_DELAY_NORMAL);     // 第一个参数是Listener,第二个参数是所得传感器类型,第三个参数值获取传感器信息的频率    }   }     @Override   protected void onPause() {    super.onPause();    if (sensorManager != null) {// 取消监听器     sensorManager.unregisterListener(sensorEventListener);    }   }     /**    * 重力感应监听    */   private SensorEventListener sensorEventListener = new SensorEventListener() {    @Override    public void onSensorChanged(SensorEvent event) {     // 传感器信息改变时执行该方法     float[] values = event.values;     float x = values[0]; // x轴方向的重力加速度,向右为正     float y = values[1]; // y轴方向的重力加速度,向前为正     float z = values[2]; // z轴方向的重力加速度,向上为正     Log.i(TAG, "x轴方向的重力加速度" + x + ";y轴方向的重力加速度" + y + ";z轴方向的重力加速度" + z);     // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。     int medumValue = 18;     if (Math.abs(x) > medumValue && Math.abs(y) > medumValue       || Math.abs(y) > medumValue && Math.abs(z) > medumValue       || Math.abs(x) > medumValue && Math.abs(z) > medumValue       ) {      vibrator.vibrate(200);      Message msg = new Message();      msg.what = SENSOR_SHAKE;      handler.sendMessage(msg);     }    }      @Override    public void onAccuracyChanged(Sensor sensor, int accuracy) {    }   };   /**    * 动作执行    */   Handler handler = new Handler() {    @Override    public void handleMessage(Message msg) {     super.handleMessage(msg);     switch (msg.what) {     case SENSOR_SHAKE:      msentence = sentence.getSentence();// 得到随机的句子      // Toast.makeText(MainActivity.this, msentence, 1).show();      tv.setText(msentence);// 将得到的句子显示在textview上      // Log.i(TAG, "检测到摇晃,执行操作!");      break;     }    }   };     @Override   protected void onDestroy() {    // TODO Auto-generated method stub    super.onDestroy();    mediaPlayer.stop(); // 退出时停止音乐     }     /**    * 键盘事件,当按下back键的时候询问是否再按一次退出程序    */   // 退出时间   private long exitTime = 0;     @Override   public boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK      && event.getAction() == KeyEvent.ACTION_DOWN) {     if ((System.currentTimeMillis() - exitTime) > 2000) {      Toast.makeText(getApplicationContext(), "再按一次退出程序",        Toast.LENGTH_SHORT).show();      exitTime = System.currentTimeMillis();     } else {      finish();      System.exit(0);       }     return true;    }    return super.onKeyDown(keyCode, event);   }     /**    * 按钮事件监听    */   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    switch (v.getId()) {    // 当按下按钮,将切换到刮一刮页面    case R.id.tv_rubber: {     Toast.makeText(MainActivity.this, "刮一刮", 1).show();     Intent rubblerIntent = new Intent(MainActivity.this,       RubblerAct.class);     startActivity(rubblerIntent);     break;    }    default:     break;    }   }    }