sensorManager对象的未定义getSystemService()函数

时间:2012-01-04 08:30:18

标签: android

我的源代码是:

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()函数。 我该怎么写呢?感谢。

2 个答案:

答案 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)
         ...
    }
}