加速度计转入后台服务



我使用了这个链接http://blog.androgames.net/85/android-accelerometer-tutorial/以创建加速度计。但我希望这个加速度计能在后台工作。所以我把代码改成这样:

public class Accelerometer extends Service implements AccelerometerListener{
private static Context CONTEXT;
@Override
public IBinder onBind(Intent intent) {
// TODO Put your code here
return null;
}
@Override
public void onCreate() {
System.out.println(”start listening”);
// if (AccelerometerManager.isSupported()) {
AccelerometerManager.startListening(this);
// }
}
@Override
public void onDestroy() {
System.out.println(”start listening”);
// if (AccelerometerManager.isListening()) {
AccelerometerManager.stopListening();
// }
}
public static Context getContext() {
return CONTEXT;
}
/**
* onShake callback
*/
public void onShake(float force) {
Toast.makeText(this, “close” + force, 1000).show();
}
/**
* onAccelerationChanged callback
*/
public void onAccelerationChanged(float x, float y, float z) {
System.out.println(”x = “+x+” y = “+y+” z = “+z);
}
}

我得到了这个错误:

 Java.lang.runtimeexception : Unable to create service com.tam.Accelerometer: java.lang.NullPointerException
Caused by: java;lang.NullPointerException

有人能帮我吗?

您需要将CONTEXT值指定为

CONTEXT = Accelerometer.this;

onCreate()方法中

Android加速计传感器你已经发布了,并得到了答案,如果是你?您需要设置上下文

this.getApplicationContext()

最新更新