2012-12-03 37 views
2

我寫了一個加速計應用程序(用於學習目的)使用StackOverflow的一些建議。一切工作正常,但我得到了「SensorManager.DATA_X已經過時」消息在我的代碼警告:Android加速度計:SensorManager.DATA_X已棄用 - 現在該怎麼辦?

// setup the textviews for displaying the accelerations 
mAccValueViews[SensorManager.DATA_X] = (TextView) findViewById(R.id.accele_x_value); 
mAccValueViews[SensorManager.DATA_Y] = (TextView) findViewById(R.id.accele_y_value); 
mAccValueViews[SensorManager.DATA_Z] = (TextView) findViewById(R.id.accele_z_value); 

我試圖尋找在這裏和其他地方我應該做的,而不是使用「SensorManager.DATA_X」的話,但我似乎無法找到任何指示。

官方指南說,使用「傳感器」,而不是我怎麼搞清楚!

如果任何人都可以建議什麼新的「官方」做上述方法,那麼我將非常感激。

編輯 後重新閱讀文檔(正常這個時候!)我注意到,「SensorManager.DATA_X」只返回一個int這是onSensorChanged返回數組中的X值的索引(INT ,float [])。我能夠改變上面的代碼到這一點,這完美的作品,沒有任何過時的警告:

// setup the textviews for displaying the accelerations 
    mAccValueViews[0] = (TextView) findViewById(R.id.accele_x_value); 
    mAccValueViews[1] = (TextView) findViewById(R.id.accele_y_value); 
    mAccValueViews[2] = (TextView) findViewById(R.id.accele_z_value); 
+0

您是否閱讀過文檔:http://developer.android.com/guide/topics/sensors/sensors_overview.html –

回答

2

的文檔是相當明確,創建您的傳感器:

private SensorManager mSensorManager; 
private Sensor mSensor; 

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); 

if (mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null){ 
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
} 

而且有你Sensor,註冊一個偵聽器來使用它:

mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); 

然後可以使用OnSensorChanged獲得values

@Override 
    public final void onSensorChanged(SensorEvent event) { 
    // Many sensors return 3 values, one for each axis. 
    float xaccel = event.values[0]; 
    // Do something with this sensor value. 
    } 
+1

嗨,謝謝你的回答。是的,我一直在關注我的onSensorChanged方法的過程,但是,後來在我重新使用的代碼中,在onCreate方法中,出現了上面發佈的代碼。我想用一些對onSensorChanged方法中定義的「event.values [i]」的引用替換「SensorManager.DATA_X」,但我似乎無法做到這一點! – BryanJ

+0

我想你將不得不用0初始化它們並將它們設置在第一個'onSensorChanged'事件中。我認爲它在註冊偵聽器後的毫秒內觸發。 –

+0

再次感謝。那麼你關於閱讀文檔的第一個評論就是現實。當我正確地重讀文檔*時,我發現「SensorManager.DATA_X」返回一個int,它是由onSensorChanged(int,float [])返回的數組中X值的索引。由於這些只是索引值,我可以用mAccValueViews [0] ....等替換mAccValueViews [SensorManager.DATA_X] .... – BryanJ