Android/傾きセンサー
提供: 初心者エンジニアの簡易メモ
- AndroidHelloworld1.java
package info.nonip.AndroidHelloworld1; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.widget.TextView; public class AndroidHelloworld1Activity extends Activity implements SensorEventListener { private SensorManager manager; private TextView values; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); values = (TextView)findViewById(R.id.text1); manager = (SensorManager)getSystemService(SENSOR_SERVICE); } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); // Listenerの解除 manager.unregisterListener(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); // Listener登録 List<Sensor> sensors = manager.getSensorList(Sensor.TYPE_ORIENTATION); if(sensors.size() > 0) { Sensor s = sensors.get(0); manager.registerListener(this, s, SensorManager.SENSOR_DELAY_UI); } } // jdk1.5以下はアノテーションを消さないとコンパイル不可能 //@Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub } // jdk1.5以下はアノテーションを消さないとコンパイル不可能 //@Override public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub String str = ""; if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) { str = "方位角:" + event.values[0] + "\n傾斜角:" + event.values[1] + "\n回転角:" + event.values[2]; values.setText(str); } } }
- layout/main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>