Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現搖一搖功能

Android實現搖一搖功能

編輯:關於Android編程

實現“搖一搖”功能,其實很簡單,就是檢測手機的重力感應,具體實現代碼如下:

1、在 AndroidManifest.xml 中添加操作權限

2、實現代碼

 package com.xs.test; 
 
import android.app.Activity; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.os.Vibrator; 
import android.util.Log; 
import android.widget.Toast; 
 
/** 
 * 安卓晃動手機監聽--“搖一搖” 
 * 
 * @author 單紅宇 
 * 
 */ 
public class TestSensorActivity extends Activity { 
 
  private SensorManager sensorManager; 
  private Vibrator vibrator; 
 
  private static final String TAG = "TestSensorActivity"; 
  private static final int SENSOR_SHAKE = 10; 
 
  /** Called when the activity is first created. */ 
  @Override 
  public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    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 = 19;// 三星 i9250怎麼晃都不會超過20,沒辦法,只設置19了 
      if (Math.abs(x) > medumValue || Math.abs(y) > 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: 
        Toast.makeText(TestSensorActivity.this, "檢測到搖晃,執行操作!", Toast.LENGTH_SHORT).show(); 
        Log.i(TAG, "檢測到搖晃,執行操作!"); 
        break; 
      } 
    } 
 
  }; 
} 

這種搖一搖比較普通,沒有經過算法的加強,重力加速度就是10。
算法優化如下

package com.example.url;


import java.io.IOException;
import java.net.URL;


import com.hahashijie.imageload.ImageLoader;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.widget.ImageView;


@SuppressLint("HandlerLeak")
public class MainActivity extends Activity {


private ImageView image;
private SensorManager sensorManager;
private Sensor sensor;
private Vibrator vibrator;
private static final int UPTATE_INTERVAL_TIME = 50;
private static final int SPEED_SHRESHOLD = 30;//這個值調節靈敏度
private long lastUpdateTime;
private float lastX;
private float lastY;
private float lastZ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
image = (ImageView) findViewById(R.id.image);


}


@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (sensorManager != null) {
      sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    }
    if (sensor != null) {
    sensorManager.registerListener(sensorEventListener,
    sensor,
SensorManager.SENSOR_DELAY_GAME);//這裡選擇感應頻率
    }
}


/**
* 重力感應監聽
*/
private SensorEventListener sensorEventListener = new SensorEventListener() {


@Override
public void onSensorChanged(SensorEvent event) {
long currentUpdateTime = System.currentTimeMillis();
long timeInterval = currentUpdateTime - lastUpdateTime;
if (timeInterval < UPTATE_INTERVAL_TIME) {
return;
}
lastUpdateTime = currentUpdateTime;
// 傳感器信息改變時執行該方法
float[] values = event.values;
float x = values[0]; // x軸方向的重力加速度,向右為正
float y = values[1]; // y軸方向的重力加速度,向前為正
float z = values[2]; // z軸方向的重力加速度,向上為正
float deltaX = x - lastX;
float deltaY = y - lastY;
float deltaZ = z - lastZ;


lastX = x;
lastY = y;
lastZ = z;
double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY
+ deltaZ * deltaZ) / timeInterval) * 100;
if (speed >= SPEED_SHRESHOLD) {
vibrator.vibrate(300);
image.setImageResource(R.drawable.running01);
}
}


@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
};

}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved