简体   繁体   English

Android Studio如何读取磁传感器

[英]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. 我有一些代码应该可以读取我的Galaxy S5上的地磁传感器,但是只要尝试启动它,它就会立即崩溃,仅说明它已崩溃。 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. 在调用setcontentView方法之后,必须实例化该变量。 So you have to do the following: 因此,您必须执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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