如何从onResume访问陀螺仪?

时间:2016-03-13 21:36:53

标签: android gyroscope

我有一些代码旨在计算用户转动太快的次数。我实现了一个陀螺仪,并在Resume上有一些代码可以收集数据,还有一些语音输出。但是,我在onResume中使陀螺仪正常工作时遇到了问题。首先,语音输出无法正常工作,并且出现故障。接下来,我仍然没有获得陀螺仪的值。

package com.example.shivamgandhi.gyrosafe;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Balance_Test_Activity extends VoiceControl implements View.OnClickListener, SensorEventListener, View.OnTouchListener {

    int n = 2;
    Button btnarray[] = new Button[n];
    private SensorManager mSensorManager;
    private Sensor default_gyro;
    private TextView textView79;
    RelativeLayout RelativeLayout;
    int count1 = 0;
    float axisX, axisY, axisZ;
    double omegaMagnitude;
    EditText ed29;
    private static final float NS2S = 1.0f / 1000000000.0f;
    private final float[] deltaRotationVector = new float[4];
    int touch = 0;

    int count2 = 0;
    int time1 = 0;
    int time2 = 0;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.balance_test);

        RelativeLayout = (RelativeLayout)findViewById(R.id.RelativeLayout4);

        btnarray[0] = (Button)findViewById(R.id.button10);
        btnarray[1] = (Button)findViewById(R.id.button20);

        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        default_gyro = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

        textView79 = (TextView)findViewById(R.id.textView79);

        ed29 = (EditText)findViewById(R.id.editText29);

        for(int i = 0; i <n; i++){
            btnarray[i].setOnClickListener(this);
        }

        RelativeLayout.setOnTouchListener(this);

    }

    //when this Activity starts
    @Override
    protected void onResume()
    {
        super.onResume();

        if (touch == 1){
            try{
                speakWords("Please place your hands on your hips and keep your feet under your shoulders. Hold your balance for the next 20 seconds");
                Thread.sleep(2000);
                while(time1 < 334){
                    mSensorManager.registerListener(this, default_gyro, SensorManager.SENSOR_DELAY_UI);
                    if(omegaMagnitude > 2){
                        count1 ++;
                        time1 ++;
                    }
                    else{
                        time1 ++;
                    }
                }
                Thread.sleep(2000);
                speakWords("Place your hands by your side. Tap to continue.");
                Thread.sleep(1000);
                touch = 10;
            }
            catch(InterruptedException e){
                e.printStackTrace();
            }
        }

        if (touch == 2){
            speakWords("Please place your hands on your hips and stand on your nondominant foot for the next 20 seconds");
            while(time2 < 334){
                mSensorManager.registerListener(this, default_gyro, SensorManager.SENSOR_DELAY_UI);
                if(omegaMagnitude > 2){
                    count2 ++;
                    time1 ++;
                }
                else{
                    time1 ++;
                }
            }
            speakWords("You may resume normal stance now");
            touch = 20;
        }


    }

    @Override
    protected void onStop()
    {
        //unregister the sensor listener
        mSensorManager.unregisterListener(this);
        super.onStop();
    }

    @Override
    public void onClick(View v){
        if(v == findViewById(R.id.button10)){
            Intent myIntent = new Intent(this, Results_Page_Activity.class);
            startActivity(myIntent);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event){
        if(v == RelativeLayout){
           if(touch == 0){
               touch = 1;
               onResume();
               return true;
           }
            else if (touch == 10){
               touch = 2;
               onResume();
               return true;
           }
            return true;
        }
        else{
            return false;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1)
    {
        //Do nothing.
    }


    public void onSensorChanged(SensorEvent event) {
        // This timestep's delta rotation to be multiplied by the current rotation
        // after computing it from the gyro sample data.

        // Axis of the rotation sample, not normalized yet.
        float axisX = event.values[0];
        float axisY = event.values[1];
        float axisZ = event.values[2];

        // Calculate the angular speed of the sample
        double omegaMagnitude = Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

        float[] deltaRotationMatrix = new float[9];
        SensorManager.getRotationMatrixFromVector(deltaRotationMatrix, deltaRotationVector);

        textView79.setText("Gyro X (Roll) :" + Float.toString(event.values[2]) + "\n" +
                "Gyro Y (Pitch) :" + Float.toString(event.values[1]) + "\n" +
                "Gyro Z (Yaw) :" + Float.toString(event.values[0]));
    }
}

如何修复此代码以便我可以实际从陀螺仪中检索值?在此先感谢:)

1 个答案:

答案 0 :(得分:0)

好的,这里有几个问题。

1)永远不要睡在onResume或UI线程上的任何其他位置。你不能这样坚持下去。最好这样做会让你看起来像你已经崩溃,最糟糕的是它会因看门狗而崩溃。它几乎永远不会做你想要的。

2)你永远不会真正设置imegaMagnitude,因为你在onSensorChanged中重新定义了它

3)无论如何你都看不到正确的值,因为在调用onSensorChanged之前它不会被设置。由于只在UI线程上调用,因此在onResume完成之后才会调用它(参见1)。所以你的代码无论如何都无法工作。

4)你不能自己打电话给Resume。只允许框架调用生命周期函数。你自己这样做会严重搞砸。

你的方法完全不合适。重写您的逻辑以使用基于事件的处理和状态机模式。这段代码不可挽救。