2013-11-18 3 views
1

Я работаю над Android-приложением, которое имеет основное действие с некоторыми текстовыми изображениями для отображения данных датчиков (чтение и отображение ускорений и данных giro). В методе onCreate я вызываю обычный Java-вызов под названием SensorModule, и я даю contect как параметр этому классу.Доступные датчики Android в классе неактивности

Класс SensorModule реализует SensorEventListener для просмотра событий датчиков. Объект создается в основном методе onCreate (у меня есть некоторые отпечатки, и я вижу их в Logcat).

Но метод onSensorChanged не вызывается. (когда я помещаю код SensorModule в основную активность, тогда он отлично работает).

Я думаю, что у меня проблема с инициализацией SensorModule и его сенсоромEventlistener, но я не знаю, в чем проблема. У кого-нибудь есть идея?

Ниже я Инициализирующий из SensorModule в OnCreate метод основной деятельности:

SensorM = new SensorModule(this); 

Вот SensorClass с, где я думаю, что что-то пойдет не так, печать в SensorOnChange не печатается в LogCat :

package com.example.SensorModuleClass; 

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

public class SensorModule implements SensorEventListener { 

    private boolean alphaStatic = true; 

    Context AppContext; 

    // Constants for the low-pass filters 
    private float timeConstant = 0.18f; 
    private float alpha = 0.1f; 
    private float dt = 0; 

    // Timestamps for the low-pass filters 
    private float timestamp = System.nanoTime(); 
    private float timestampOld = System.nanoTime(); 

    private int count = 0; 

    // Gravity and linear accelerations components for the 
    // Wikipedia low-pass filter 
    private float[] gravity = new float[] 
    { 0, 0, 0 }; 

    private float[] linearAcceleration = new float[] 
    { 0, 0, 0 }; 

    // Raw accelerometer data 
    private float[] input = new float[] 
    { 0, 0, 0 }; 


    // device sensor manager 
    public static SensorManager mSensorManager; 
    public static SensorEventListener mSensorListener; 

    // Outputs for the acceleration and LPFs 
    public float[] AccelerationData = new float[3]; 
    public float[] AccelerationResult = new float[3]; 

    public SensorModule(Context Context){ 

     System.out.println("#### Constructor"); 

     AppContext = Context; 

     // initialize your android device sensor capabilities 
     //mSensorManager = (SensorManager) AppContext.getSystemService(Context.SENSOR_SERVICE); 
     SensorManager mSensorManager = (SensorManager) AppContext.getSystemService(Context.SENSOR_SERVICE); 

     System.out.println("#### Constructor done"); 
    } 

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

    } 

    @Override 
    public void onSensorChanged(SensorEvent event) { 

     System.out.println("=======On changed called====="); 
     // Get a local copy of the sensor values 
     System.arraycopy(event.values, 0, AccelerationData, 0, event.values.length);  

     AccelerationData[0] = AccelerationData[0]/SensorManager.GRAVITY_EARTH; 
     AccelerationData[1] = AccelerationData[1]/SensorManager.GRAVITY_EARTH; 
     AccelerationData[2] = AccelerationData[2]/SensorManager.GRAVITY_EARTH; 

     // Get result 
     AccelerationResult = GetAcceleration(AccelerationData); 
    } 

    public float[] GetAcceleration(float[] AccelData){ 

     // Get a local copy of the sensor values 
     System.arraycopy(AccelData, 0, this.input, 0, AccelData.length); 

     // 
     count++; 

     if (count > 5) 
     { 
      // Update the Wikipedia filter 
      // y[i] = y[i] + alpha * (x[i] - y[i]) 
      // Get gravity values 
      gravity[0] = gravity[0] + alpha * (this.input[0] - gravity[0]); 
      gravity[1] = gravity[1] + alpha * (this.input[1] - gravity[1]); 
      gravity[2] = gravity[2] + alpha * (this.input[2] - gravity[2]); 


      // Use gravity values to get the acceleration by substracting the 
      // gravity from the input signel(the raw acceleration data) 
      linearAcceleration[0] = input[0] - gravity[0]; 
      linearAcceleration[1] = input[1] - gravity[1]; 
      linearAcceleration[2] = input[2] - gravity[2]; 
     } 

     // Return the acceleration values of the x, y and z axis 
     return linearAcceleration; 
    } 

} 

Любые предложения и отзывы приветствуются!

ответ

1

SensorM = new SensorModule(getApplicationContext);
использовать как этот

еще пытаются изменить свой код, как это

public class SensorActivity extends Activity, implements SensorEventListener { 
    private final SensorManager mSensorManager; 
    private final Sensor mAccelerometer; 

    public SensorActivity() { 
     mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); 
     mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
    } 

    protected void onResume() { 
     super.onResume(); 
     mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); 
    } 

    protected void onPause() { 
     super.onPause(); 
     mSensorManager.unregisterListener(this); 
    } 

    public void onAccuracyChanged(Sensor sensor, int accuracy) { 
    } 

    public void onSensorChanged(SensorEvent event) { 
    } 
} 
+0

Спасибо за ваш комментарий, я изменил инициализации объекта в onCreateMethod для: SensorM = новый SensorModule (getApplicationContext()) ;. Но onSensorChanged все еще не вызван. – Roy08

+0

Спасибо, что попробуй. Один вопрос: могу ли я просто вызвать конструктор в методе onCreate основной активности? Например: SensrActivity SensorAct = новый SensorActivity(); ? – Roy08

+0

Я думаю, что вы можете это сделать.http: //www.vogella.com/articles/AndroidSensor/article.html ссылку – Ruban

Смежные вопросы