Presentation is loading. Please wait.

Presentation is loading. Please wait.

加速感測器 靜宜大學資管系 楊子青.

Similar presentations


Presentation on theme: "加速感測器 靜宜大學資管系 楊子青."— Presentation transcript:

1 加速感測器 靜宜大學資管系 楊子青

2 1.認識加速感測器

3 手機傾斜

4 2.取得系統的感測器物件

5 讀取感測器的加速度值

6 註冊/解除監聽事件

7 3.建立Sensor專案,讀取加速度值 原本的TextView id: @+id/txv textSize: 20sp
public class MainActivity extends AppCompatActivity implements SensorEventListener { SensorManager sm; Sensor sr; TextView txv;

8 設定SensorManager與Sensor
@Override protected void onCreate(Bundle savedInstanceState) { sm = (SensorManager) getSystemService(SENSOR_SERVICE); sr = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); txv = (TextView) findViewById(R.id.txv); }

9 註冊/解除監聽 @Override public void onResume(){ super.onResume();
sm.registerListener(this, sr, SensorManager.SENSOR_DELAY_NORMAL); } public void onPause(){ super.onPause(); sm.unregisterListener(this);

10 讀取x、y、z軸加速度之值 @Override
public void onSensorChanged(SensorEvent event){ float x, y, z; x = event.values[0]; y = event.values[1]; z = event.values[2]; txv.setText(String.format("x軸: %1.2f \ny軸: %1.2f \nz軸: %1.2f", x, y, z)); } public void onAccuracyChanged(Sensor sensor, int accuracy){

11 螢幕強制為直向 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="tw.edu.pu.csim.tcyang.sensor"> <application android:allowBackup="true" android:supportsRtl="true" <activity android:name=".MainActivity" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

12 4.利用加速感測器來做體感控制 偵測手機面朝下平放的狀態 偵測手機搖晃的狀態
if (Math.abs(x)<1 && Math.abs(y)<1 && z<-9) { txv.setText("朝下平放"); } 偵測手機搖晃的狀態 if (Math.abs(x) + Math.abs(y) + Math.abs(z) > 32) { txv.setText(“手機搖晃");

13 修改專案程式碼 public void onSensorChanged(SensorEvent event){ float x, y, z;
x = event.values[0]; y = event.values[1]; z = event.values[2]; //txv.setText(String.format("x軸: %1.2f, y軸: %1.2f, z軸: %1.2f", x, y, z)); if (Math.abs(x)<1 && Math.abs(y)<1 && z<-9) { txv.setText("朝下平放"); } else if (Math.abs(x) + Math.abs(y) + Math.abs(z) > 32){ txv.setText("手機搖晃");


Download ppt "加速感測器 靜宜大學資管系 楊子青."

Similar presentations


Ads by Google