我的源码是:
import android.content.Context;
import android.hardware.SensorManager;
public class ShakeEvent implements SensorEventListener {
private static SensorManager sensorManager;
...
...
public static boolean isSupported (){
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);我收到错误消息,指出getSystemService函数定义不足。我试着用这样的方式来写这行:
sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);但随后我收到错误消息,指出ShakeEvent对象的getContext()函数未定义。我该怎么写呢?谢谢。
发布于 2012-01-04 16:42:33
您的类似乎没有引用任何Context对象。getSystemService()是一种Context方法,因此在创建SensorEventListener时需要对上下文对象(如Activity)的引用。然后你就可以调用context.getSystemService()了。
import android.content.Context;
import android.hardware.SensorManager;
public class ShakeEvent implements SensorEventListener {
private static SensorManager sensorManager;
private final Context context;
public ShakeEvent(Context context) {
this.context = context;
}
...
...
public static boolean isSupported (){
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);发布于 2012-01-04 16:42:43
您需要将上下文对象传递给此类并调用getSystemService(..)在它上面
public class ShakeEvent implements SensorEventListener {
private static SensorManager sensorManager;
private Context mCtx;
...
public ShakeEvent(Context ctx) {
this.mCtx = ctx;
}
public static boolean isSupported (){
sensorManager = (SensorManager) mCtx.getSystemService(Context.SENSOR_SERVICE)
...
}
}https://stackoverflow.com/questions/8723980
复制相似问题