创建类的实例不会执行onCreate

时间:2018-03-18 14:00:53

标签: android android-sensors magnetometer

这可能是一个非常基本的问题,但我一直在努力解决它。

我正在尝试创建一个处理android磁力计的类的实例。 我已经设置了课程,但现在我需要使用它。

这是班级

public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mMagnetometer;

@Override
public final void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    LayoutInflater inflater = getLayoutInflater();    // just to see if this really executes
    View myView = inflater.inflate(R.layout.activity_main, null);
    TextView myTextView = (TextView) findViewById(R.id.textview);
    myTextView.setText("done");

}

@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
    // Do something here if sensor accuracy changes.
}

@Override
public final void onSensorChanged(SensorEvent event) {

    float magnetic_field = event.values[0];
    String m = Float.toString(magnetic_field);
                        // Update textview with values
    LayoutInflater inflater = getLayoutInflater();
    View myView = inflater.inflate(R.layout.activity_main, null);
    TextView myTextView = (TextView) findViewById(R.id.textview);
    myTextView.setText("done");

}

@Override
protected void onResume() {
    super.onResume();
    mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}

}

现在我通过在MainActivity onCreate()

中实现这个类来实现它
SensorActivity mSensorActivity = new SensorActivity();

什么都没发生。如果这没有运行,我将放弃该类,因为我已经通过直接访问SensorManager和传感器获得了一些东西

0 个答案:

没有答案