0
我正在嘗試使用背景服務來讀取手機的方位角,俯仰角和滾動角並通過網絡發送它們。我已經創建了一個IntentService
和計算代碼來計算方向,但是我不太確定我是如何將後臺服務註冊爲事件監聽器的。如何在Android中註冊後臺服務作爲SensorEventListener
public class SocketService extends IntentService implements SensorEventListener {
Socket my_socket;
PrintWriter out;
float[] mGravity;
float[] mGeomagnetic;
float azimuth,pitch,roll;
public void onAccuracyChanged(Sensor s, int accuracy){
}
public void onSensorChanged(SensorEvent event){
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
mGravity = event.values;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
mGeomagnetic = event.values;
if (mGravity != null && mGeomagnetic != null) {
float R[] = new float[9];
float I[] = new float[9];
boolean success = SensorManager.getRotationMatrix(R, I, mGravity, mGeomagnetic);
if (success) {
float orientationData[] = new float[3];
SensorManager.getOrientation(R, orientationData);
azimuth = orientationData[0];
pitch = orientationData[1];
roll = orientationData[2];
out.print("Hello");
out.flush();
}
}
}
public SocketService(){
super("Socket Service");
}
protected void onHandleIntent(Intent workIntent) {
try {
my_socket = new Socket(ip, 5000);
out = new PrintWriter(my_socket.getOutputStream());
}catch(Exception e){
Log.v("ERROR",e.getMessage());
}
}
}
我曾嘗試onHandleIntent
內把
Sensor mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor mGravity = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
mSensorManager.registerListener(this,mAccelerometer,SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this,mGravity,SensorManager.SENSOR_DELAY_FASTEST);
來編譯但是沒有數據在插座的另一端檢測到的(沒有檢測到的數據,即使我嘗試記錄它,所以必須有一個問題與實際SensorEventListener
它適用於我,你在什麼地方放點完全? mSensorManager.registerListener(this,...) – jbarat
@jbarat對不起。我更新了問題 – Bula
只是爲了確定代碼是否是別的問題,如果將此代碼放入活動中,它是否有效? – jbarat