android之加速感應器

使用加速感應器的三個步驟,我們需要實現接口SensorEventListener:

1.獲得感應器管理對象:sensorManager=(SensorManager) ball.getSystemService(context.SENSOR_SERVICE);

ball表示一個Activity類。

2.獲得加速感應器對象:sensor=sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);

3.注冊監聽器:sensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_GAME);

當感應到加速度變化時,會自動調用以下方法:onSensorChanged


加速感應器應用之重力球:

Activity類:

public class GravityBallActivity extends Activity{

private MyView myView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gravity_ball);

myView=new MyView(getApplicationContext(),this);
myView.setFocusable(true);
setContentView(myView);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}

View類,繪制小球:

public class MyView extends View implements SensorEventListener {
private Canvas canvas;
private Paint paint;
private SensorManager sensorManager;
private Sensor sensor;

//初始加速度值
private float AccelX=0;
private float AccelY=0;
private float AccelZ=0;

//變化後的加速度
private float last_AccelX=0;
private float last_AccelY=0;
private float last_AccelZ=0;
private long lastUpdate=0;

//小球的位置
private float ballX=0,ballY=0;

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//該函數作用是使整個客戶區域無效,客戶區無效意味著需要重新繪制
invalidate();
canvas.drawCircle(ballX, ballY, 50, paint);
}


//屏幕大小
int screenWidth=0,screenHeight=0;

public MyView(Context context, GravityBallActivity ball) {
super(context);
canvas=new Canvas();
paint=new Paint();
paint.setColor(Color.RED);
sensorManager=(SensorManager) ball.getSystemService(context.SENSOR_SERVICE);
sensor=sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
sensorManager.registerListener(this, sensor,SensorManager.SENSOR_DELAY_GAME);
// TODO Auto-generated constructor stub
}


@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
        //得到加速度值
AccelX=event.values[SensorManager.DATA_X];
AccelY=event.values[SensorManager.DATA_Y];
AccelZ=event.values[SensorManager.DATA_Z];

//得到當前屏幕的寬高
screenWidth=this.getWidth();
screenHeight=this.getHeight();

//小球運動的中心坐標,因為在模擬重力小球時隻是感應方向的變化,
//我們取小球位置的變化在數值上等於加速度的變化
ballX-=AccelX;
ballY-=AccelY;

if(ballX<0)
{
ballX=0;
}else if(ballX>screenWidth)
{
ballX=screenWidth;
}
if(ballY<0)
{
ballY=0;
}else if(ballY>screenHeight)
{
ballY=screenHeight;
}
onDraw(canvas);
}


@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}


}

你可能感兴趣的:(android之加速感應器)