每当我尝试运行它时,它都会崩溃。我不知道问题可能出在哪里。我是否遗漏了某些东西或某些东西在错误的地方?在 logcat 中,它说系统服务在 oncreate 之前对活动不可用。
import android.os.Bundle;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.view.Menu;
import android.widget.*;
import android.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class MainActivity extends Activity implements SensorEventListener {
private final SensorManager mSensorManager;
private final Sensor mRotationVector;
public float x,y,z;
public MainActivity(){
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mRotationVector, SensorManager.SENSOR_DELAY_GAME);
}
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
x= event.values[0];
y= event.values[1];
z= event.values[2];
TextView mTextView0 = (TextView) findViewById(R.id.textView0);
mTextView0.setText("x"+x);
TextView mTextView1 = (TextView) findViewById(R.id.textView1);
mTextView1.setText("y"+y);
TextView mTextView2 = (TextView) findViewById(R.id.textView2);
mTextView2.setText("z"+z);
}
}