简体   繁体   中英

android studio how to read magnetic sensor

I have some code I should think would work to readout the geomagnetic sensor on my Galaxy S5, but whenever it attempts to launch it immediately crashes simply stating that it crashed. I don't know what the problem might be with the code, but there doesn't seem to be any errors. any ideas?

package com.gmail.~~~~~~~~.magnetictest;

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 android.widget.TextView;

public class MainActivity extends AppCompatActivity implements     SensorEventListener {

private SensorManager mSensorManager;
private Sensor mSensor;
TextView Mtext;

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

    mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mSensorManager.registerListener(this, mSensor, mSensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void onSensorChanged(SensorEvent event) {
    Mtext.setText(String.valueOf(event.values[0]));
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {

}
}

You have to instantiate the variable after the setcontentView method was called. So you have to do the following:

Mtext = (TextView)findViewById(R.id.<textview id from activity main>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM