2015-01-21 3 views
0

Я новичок, и я вообще не понимаю, как использовать датчики. Моя цель - на данный момент получить данные о датчике вращения на Activity. Я хотел бы использовать векторы вращения, но я не видел here, что они больше не были доступны на андроид 4.1.2 ... код у меня до сих пор:Как использовать датчики на Android?

package thomas.drone; 

import android.app.Activity; 
import android.content.Intent; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.view.View; 
import android.view.Window; 
import android.view.WindowManager; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 


public class MainActivity extends Activity implements View.OnClickListener { 
    public Button boutonPilote; 
    TextView xminus=null; 
    TextView yminus=null; 
    TextView xplus=null; 
    TextView yplus = null; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    /*On déclare les capteurs que l'on veut utiliser*/ 
    SensorManager sMgr; 
    sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); 
    Sensor motion; 
    motion = sMgr.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); //Ici un type Vecteur de rotation 

    /**Permet de faire du Full screen sans activity spéciale*/ 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 
    setContentView(R.layout.activity_main); 

     /*On va relier les textes du layout aux valeurs de nos TextViews*/ 
    xminus = (TextView) findViewById(R.id.xminus); 
    yminus = (TextView) findViewById(R.id.yminus); 
    xplus = (TextView) findViewById(R.id.xplus); 
    yplus = (TextView) findViewById(R.id.yplus); 

    /*** On écoute le bouton Pilote/auto, qui switch d'une activité à l'autre**/ 
    boutonPilote = (Button) findViewById(R.id.bpilote); 
    boutonPilote.setOnClickListener(this); 

    /* et on active/enregistre le capteur*/ 
    sMgr.registerListener((android.hardware.SensorEventListener) this, motion,SensorManager.SENSOR_DELAY_NORMAL); 


} 

public void onAccuracyChanged(Sensor sensor, int accuracy) { 

} 
public void onSensorChanged(SensorEvent event) { 
    Toast.makeText(getApplicationContext(), "Ca marche !", Toast.LENGTH_LONG).show(); 
} 

@Override 
public void onClick(View v) { 
    Intent i1 = new Intent(this, ModeAuto.class); 
    this.startActivity(i1); 
} 
} 

Извините за комментариями, я французский (никто не совершенен :) но сбой приложения ...

Вот файл XML, но я не думаю, что проблема исходит от него: `

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/xminus" 
    android:layout_toStartOf="@+id/yplus" 
    android:layout_marginRight="43dp" 
    android:typeface="monospace" 
    android:textSize="14sp" 
    android:textColor="@color/blanc" 
    android:text="@string/xmoins" 
    android:layout_alignBaseline="@+id/xplus" 
    android:layout_alignBottom="@+id/xplus" 
    android:layout_toLeftOf="@+id/yplus" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:id="@+id/yminus" 
    android:typeface="monospace" 
    android:textSize="14sp" 
    android:textColor="@color/blanc" 
    android:text="@string/yminus" 
    android:layout_alignBottom="@+id/bdecollage" 
    android:layout_alignLeft="@+id/yplus" 
    android:layout_alignStart="@+id/yplus" /> 

<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textAppearance="?android:attr/textAppearanceSmall" 
    android:id="@+id/xplus" 
    android:layout_toEndOf="@+id/yminus" 
    android:typeface="monospace" 
    android:textSize="14sp" 
    android:textColor="@color/blanc" 
    android:text="@string/xplus" 
    android:layout_toStartOf="@+id/bleft" 
    android:layout_alignTop="@+id/bleft" 
    android:layout_toLeftOf="@+id/bleft" /> 

`

Спасибо, Томас

+0

Сообщение logcat с крахом – skywall

ответ

0

Делать это

sMgr.registerListener((android.hardware.SensorEventListener) this, .... 

во многих случаях довольно опасно, и это, вероятно, вызывает ваши сбои. Вы должны реализовать интерфейс SensorEventListener, а затем реализовать определенные методы.

Ваш Activity класс должен выглядеть следующим образом:

public class MainActivity extends Activity implements View.OnClickListener, SensorEventListener { 

    // ... 

    @Override 
    public void onSensorChanged(SensorEvent event) { 
    // ... 
    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 

    } 
} 

Следующая проблема, вы не знаете разницу между @+id/bleft и @id/bleft. Определение с символом плюс создает новый идентификатор с заданным именем. Используйте его только при первом вхождении в xml-файл. В других случаях опустить плюс символ.

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