每当我尝试运行它时,它会崩溃。我不知道问题出在哪里。我错过了什么或者是错误的地方吗?在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);
}
}
答案 0 :(得分:4)
system services are not avaliable to activities before oncreate
你的LogCat告诉你一切!
所以改为
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
并删除此构造函数public MainActivity()
。
答案 1 :(得分:1)
你有没有为你的活动添加一个构造函数?没有必要,只需在onCreate()中执行此操作即可。只需初始化TextViews全局
private TextView mTextView0;
private TextView mTextView1;
private TextView mTextView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView0 = (TextView) findViewById(R.id.textView0);
mTextView1 = (TextView) findViewById(R.id.textView1);
mTextView2 = (TextView) findViewById(R.id.textView2);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mRotationVector = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}