我的源代码是:
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);
Run Code Online (Sandbox Code Playgroud)
我收到错误消息,指出 getSystemService 函数未定义。我也尝试以这种方式写这一行:
sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
Run Code Online (Sandbox Code Playgroud)
但随后我收到错误消息,指出 ShakeEvent 对象的 getContext() 函数未定义。我该怎么写呢?谢谢。
您的类似乎没有引用任何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);
Run Code Online (Sandbox Code Playgroud)