我得到了这个加速度计类,它保存加速度计的值,我可以随时从任何其他类访问它们。通常我会创建新对象Accelerometer accelerometer = new Accelerometer(this);
,但是当我在里面时WallpaperService
,它不允许我this
用作参数。
这是加速度计类:
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class Accelero implements SensorEventListener {
private float xAxis;
private float yAxis;
private float zAxis;
SensorManager manager;
Sensor accelerometer;
Activity activity;
public Accelero(Activity activity) {
this.activity = activity;
manager = (SensorManager) this.activity.getSystemService(Context.SENSOR_SERVICE);
accelerometer = manager.getSensorList(Sensor.TYPE_ACCELEROMETER).get(0);
manager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_GAME);
}
public float getX(){
return this.xAxis;
}
public float getY(){
return this.yAxis;
}
public float getZ(){
return this.zAxis;
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
public void onSensorChanged(SensorEvent event) {
xAxis = event.values[0];
yAxis = event.values[1];
zAxis = event.values[2];
}
}
例如,我尝试从 SDK 附带的示例代码 CubeWallpaper 中访问它
import com.example.android.livecubes.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.SystemClock;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
/*
* This animated wallpaper draws a rotating wireframe cube.
*/
public class CubeWallpaper1 extends WallpaperService {
private final Handler mHandler = new Handler();
Accelero acc;
@Override
public void onCreate() {
super.onCreate();
acc = new Accelero(this);
}
@Override
public void onDestroy() {
super.onDestroy();
}
... // skipped to keep post short.
}