2010-08-18 40 views

回答

5
+0

是啊,我發現的文件中。還有兩個問題:你將R和值初始化爲什麼?另外,是否有獲取通知的方法,或者是否已棄用整個工作模型? – 2010-08-19 03:44:38

+1

好的,在源代碼中找到了一個很好的例子。我不會在這裏複製它,但如果你瀏覽Android的git倉庫,看看開發/樣本/指南針/ src/com/example/android/compass/CompassActivity.java的末尾 – 2010-08-19 15:54:13

+1

通知/事件是一個糟糕的方式做傳感器,這就是爲什麼它是depacated afaik。每一個細微的方面變化都會觸發大量的事件,實質上是用數據扼殺UI線程。 – CodeFusionMobile 2010-08-20 14:08:11

8

以下是獲得羅盤航向,並將其顯示在一個TextView一個基本的例子來使用。它通過實現SensorEventListener接口來實現。您可以通過更改以下代碼行中的常量(即「mSensorManager.registerListener(this,mCompass,SensorManager.SENSOR_DELAY_NORMAL);」)(參見OnResume()事件)來更改事件傳遞到系統的速率。但是,這個設置只是對系統的一個建議。此示例還使用onReuse()和onPause()方法,通過在不使用時註冊和取消註冊監聽器來延長電池壽命。希望這可以幫助。

package edu.uw.android.thorm.wayfinder; 

import android.app.Activity; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.widget.TextView; 

public class CSensorActivity extends Activity implements SensorEventListener { 
private SensorManager mSensorManager; 
private Sensor mCompass; 
private TextView mTextView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.layoutsensor); 
    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE); 
    mCompass = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); 
    mTextView = (TextView) findViewById(R.id.tvSensor); 
} 

// The following method is required by the SensorEventListener interface; 
public void onAccuracyChanged(Sensor sensor, int accuracy) {  
} 

// The following method is required by the SensorEventListener interface; 
// Hook this event to process updates; 
public void onSensorChanged(SensorEvent event) { 
    float azimuth = Math.round(event.values[0]); 
    // The other values provided are: 
    // float pitch = event.values[1]; 
    // float roll = event.values[2]; 
    mTextView.setText("Azimuth: " + Float.toString(azimuth)); 
} 

@Override 
protected void onPause() { 
    // Unregister the listener on the onPause() event to preserve battery life; 
    super.onPause(); 
    mSensorManager.unregisterListener(this); 
} 

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

以下是相關的XML文件:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/tvSensor" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Large Text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

</LinearLayout> 
+3

這是否仍然使用OP提到的棄用的方向傳感器? – Tim 2013-02-25 16:14:40

+0

是的 - 不推薦使用。 – Vaiden 2013-05-19 08:44:10