2014年12月2日 星期二

[Android Sample Code] 利用Sensor物件監測三軸加速度

講解待補

package com.example.sensortest;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements SensorEventListener{
 private TextView resulFromAccelerometertTextView;
 private SensorManager mSensorManager;
 private Sensor mSensor;
 private static final int factor = 10;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        setUpAcceleratorSensor();
    }

    @Override  
    protected void onResume() {    
     super.onResume();    
     setUpAcceleratorSensor();
     mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL); 
    }
    
    @Override
    protected void onPause() { 
     super.onPause();  
     mSensorManager.unregisterListener(this);
    }

    private void findViews(){
     resulFromAccelerometertTextView = (TextView) findViewById(R.id.resulFromAccelerometertTextView);
    }
    private void setUpAcceleratorSensor(){
     mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
     if((mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)) != null);
     else
      Toast.makeText(this, "No Sensor Device Exist", Toast.LENGTH_LONG).show();
   }
   
 @Override
 public void onSensorChanged(SensorEvent event) {
  Sensor mySensor = event.sensor;
     if (mySensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      if(event.values[0]/factor > 1 || event.values[1]/factor > 1 || event.values[2]/factor > 1){ 
       resulFromAccelerometertTextView.setText("Detect your montion\n");
       resulFromAccelerometertTextView.append("X axis acceleration:" + event.values[0] + "\n");
       resulFromAccelerometertTextView.append("Y axis acceleration:" + event.values[1] + "\n");
       resulFromAccelerometertTextView.append("Z axis acceleration:" + event.values[2] + "\n");
      }
     }
 }

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

App的執行結果如下圖Fig. 1所示:

Fig. 1. 程式執行結果

沒有留言:

張貼留言