我得到了这个包含加速度计值的Accelerometer类,我可以随时从任何其他类访问它们。通常我会创建新对象Accelerometer accelerometer = new Accelerometer(this);
,但当我在WallpaperService
内时,它不允许我使用this
作为参数。
这是Acclerometer类:
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.
}
答案 0 :(得分:1)
您必须将Activity object
传递给Accelerometer类,而不是WallpaperService object
。
初始化Accelerometer对象的选项:
1)直接在onCreate()方法的活动类中执行:
Accelerometer accelerometer = new Accelerometer(this);
2)或者你可以从你的WallpaperService类中完成它,但你需要引用你的活动类。
Activity foo;
Accelerometer accelerometer = new Accelerometer(foo);
您可以在WallpaperService中创建一个方法,将活动对象的引用传递给WallpaperService对象。
public void setActivity(Activity foo) {
this.foo = foo;
}
我希望这有帮助!
<强>更新强>
这里有一些代码可以使第二个选项更容易理解:
public class YourWallPaperService extends WallpaperService {
Activity foo;
// I'm guessing you create a WallpaperService object in your activity code? If so, call this method on that object with a parameter "this"
public void setActivity(Activity foo) {
this.foo = foo;
}
}