我的源代码是:
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()函数。 我该怎么写呢?感谢。
答案 0 :(得分:4)
您的类似乎没有引用任何Context
对象。 getSystemService()
是Context
方法,因此在创建Activity
时需要引用上下文对象(如SensorEventListener
)。然后,您就可以致电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);
答案 1 :(得分:3)
您需要将Context对象传递给此类并在其上调用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)
...
}
}