package com.example.ben.droidmice2;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.example.ben.droidmice2.net.NetworkTask;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private long lastUpdate = 0;
private static final float TILT_THRESHOLD = 1.1f;
private SensorManager sensorManager;
//sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void getAccelerometer(SensorEvent event) {
Sensor mySensor = event.sensor;
if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
float x = event.values[0];
float y = event.values[1];
//float z = event.values[2];
long curTime = System.currentTimeMillis();
if ((curTime - lastUpdate) > (1000/60)) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
if(Math.abs(x) > TILT_THRESHOLD || Math.abs(y) > TILT_THRESHOLD) {
int dx = (int)(x * diffTime);
int dy = (int)(y * diffTime);
new NetworkTask().execute("MOVE " + dx + "," + dy);
}
}
}
}
@Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(sensorEvent);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
// Ignorable
}
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onResume(){
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
}
}
我正在尝试制作一个可以移动手机并使手机像鼠标一样的应用程序 这是我的代码,告诉我我有一些问题 尝试在空对象引用上调用虚拟方法'android.hardware.Sensor android.hardware.SensorManager.getDefaultSensor(int)' 对我来说,这里的OnResume()里面没有问题 有人帮忙吗?