문제

I have an app that I want to incorporate Sensor data into. My first step has been to create an app that just reads the sensor data and displays it on screen. Most of the research I've done points to tutorials such as Lars Vogel's. Unfortunately, that's where I'm stuck. I've basically copy-pasted his code into my project, and though the app runs, it doesn't display any data.

Here's the code I'm using:

package com.example.sensortest;    

import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class sensortest extends Activity implements SensorEventListener{
    private SensorManager mSensorManager;
    private Sensor mSensor;
    RelativeLayout rlsensortest; 
    TextView tvOutput;
    Button btnStart, btnStop;
    Boolean blnScan=false;

    private Handler mHandler = new Handler();
    private long mStartTime=0L;
    private long lElapsedTime=0;

    private boolean color = false;
    private long lastUpdate;        

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        //mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);       

        LayoutInflater layoutInflater = this.getLayoutInflater();

        rlsensortest = (RelativeLayout) layoutInflater.inflate(R.layout.activity_asphalt_alert,null);       
        tvOutput = (TextView) rlsensortest.findViewById(R.id.txtOutput);        
        tvOutput.setText("Initialized...\n");

        btnStart = (Button) rlsensortest.findViewById(R.id.btnStart);
        btnStop = (Button) rlsensortest.findViewById(R.id.btnStop);

        btnStart.setOnClickListener(mButtonListener);
        btnStop.setOnClickListener(mButtonListener);

        lastUpdate = System.currentTimeMillis();

        setContentView(rlsensortest);        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_asphalt_alert, menu);
        return true;
    }
    // Create an anonymous implementation of OnClickListener
    private OnClickListener mButtonListener = new OnClickListener() {
        String strMessage ="";
        public void onClick(View v) {
            if (v == btnStart){
                strMessage = "Starting sensor scan.";
                blnScan=true;
            //  mStartTimer();

            } else if (v == btnStop){
                strMessage = "Stoping sensor scan.";
                blnScan=false;
            //  mStopTimer();
            }
            if (strMessage != "")
                Toast.makeText(rlsensortest.getContext(), strMessage, Toast.LENGTH_SHORT).show();

            strMessage = "";
        }
    };



    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSensorChanged(SensorEvent event) {
/*      String strEvent = "";
        strEvent = "this is a test";
        tvOutput.setText(tvOutput.getText() + strEvent + "Another line\n"); */

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            getAccelerometer(event);
        }       

    }
    private void getAccelerometer(SensorEvent event) {
        float[] values = event.values;
        // Movement
        float x = values[0];
        float y = values[1];
        float z = values[2];

        float accelationSquareRoot = (x * x + y * y + z * z)
            / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
        long actualTime = System.currentTimeMillis();
        if (accelationSquareRoot >= 2) //
        {
          if (actualTime - lastUpdate < 200) {
            return;
          }
          lastUpdate = actualTime;
          Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
              .show();
          if (color) {
            tvOutput.setBackgroundColor(Color.GREEN);

          } else {
            tvOutput.setBackgroundColor(Color.RED);
          }
          color = !color;
        }
      } 
}

At this point, when the phone is shaken, it should (at least) give a toast that says the event happened. Any idea what I'm doing wrong? Any help is appreciated

도움이 되었습니까?

해결책

It looks like you're never doing anything with mSensorManager. You need to get a Sensor from it before you can receive SensorEventListener callbacks. Acquiring/releasing Sensors typically happens in onResume/onPause.

Example from Lars Vogel's Sensor tutorial:

  @Override
  protected void onResume() {
    super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
    mSensorManager.registerListener(this,
        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_NORMAL);
  }

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

다른 팁

Add to your Activity:

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

@Override
protected void onPause() {
    super.onPause();
    mSensorManager.unregisterListener(this);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top