簡體   English   中英

無法在Android Studio中識別sensorEvent

[英]sensorEvent is not recognized in android studio

我正在嘗試為Android片段制作一個指南針。 我在線上學習了一些課程,並閱讀了文檔,但標題中卻出現了錯誤。

我的代碼是這樣的:

 public void onSensorChanged(SensorEvent event) {
    final float alpha = 0.97f;

    synchronized (this){

        if(sensorEvent.sensor.getType()  == Sensor.TYPE_ACCELEROMETER){
            mGravity[0] = alpha * mGravity[0] + (1 - alpha) * sensorEvent.values[0];
            mGravity[1] = alpha * mGravity[1] + (1 - alpha) * sensorEvent.values[1];
            mGravity[2] = alpha * mGravity[2] + (1 - alpha) * sensorEvent.values[2];


        }
        if(sensorEvent.sensor.getType()  == Sensor.TYPE_MAGNETIC_FIELD){
            mGeomagnetic[0] = alpha * mGeomagnetic[0] + (1 - alpha) * sensorEvent.values[0];
            mGeomagnetic[1] = alpha * mGeomagnetic[1] + (1 - alpha) * sensorEvent.values[1];
            mGeomagnetic[2] = alpha * mGeomagnetic[2] + (1 - alpha) * sensorEvent.values[2];
        }

        float R[] = new float[9];
        float I[] = new float[9];
        boolean succes = SensorManager.getRotationMatrix(R,I, mGravity, mGeomagnetic);

        if(succes){
            float orientation[] = new float[3];
            SensorManager.getOrientation(R, orientation);
            azimuth = (float) Math.toDegrees(orientation[0]);
            azimuth = (azimuth + 360) % 360;

            Animation animation = new RotateAnimation(-correctAzimuth, azimuth, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            correctAzimuth = azimuth;
            animation.setDuration(500);
            animation.setFillAfter(true);
            imageBoussole.startAnimation(animation);
        }

    }
}

在同步塊中,即使是android studio也無法識別sensorEven。 這是我的進口商品:

import android.content.Context; 
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

代碼中的sensorEvent首次出現在這里:

if(sensorEvent.sensor.getType()  == Sensor.TYPE_ACCELEROMETER){

在清單中代碼的任何地方都沒有定義sensorEvent 毫不奇怪,Android Studio不知道如何處理它。

您將參數命名為方法event ,而不是sensorEvent

public void onSensorChanged(SensorEvent event) {

因此,將其更改為:

public void onSensorChanged(SensorEvent sensorEvent) {

或者, sensorEvent所有引用更改為event 方法參數和您對該參數的使用需要匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM