2012年12月15日 星期六

距離感應器最佳化


package com.example.testlight;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener, Runnable {

    private static final String TAG = "MainActivity";
    private SensorManager mgr;
    private Sensor proximity;
    private Vibrator vibrator;
    private float lastVal = -1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d(MainActivity.TAG, "onCreate...");
        // Android 所有的感應器的統一介面
        this.mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        // 取得距離感應器
        this.proximity = this.mgr.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        // 用振動來反應距離的變化
        this.vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(MainActivity.TAG, "registerListener...");
        // 一定要在這註冊
        this.mgr.registerListener(this, this.proximity,
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
       // Log.d(MainActivity.TAG, "unregisterListener...");
        // 一定要在這解註冊
       // this.mgr.unregisterListener(this, this.proximity);
    }
    private Handler handler = new Handler();
    @Override
    public void onSensorChanged(SensorEvent event) {
        Log.d(MainActivity.TAG, "onSensorChanged...");
        // 目前的距離
        float thisVal = event.values[0];
        if (this.lastVal == -1) {
            // 第一次進來
            this.lastVal = thisVal;
        }
        else {
            if (thisVal < this.lastVal) {
                // 接近長振動
                this.vibrator.vibrate(1000);
            }
            else {
                // 離開短振動
                this.vibrator.vibrate(100);
            }
            handler.postDelayed(this, 3*1000);
            this.lastVal = thisVal;
        }
        String msg = "Current val: " + this.lastVal;
        Log.d(MainActivity.TAG, msg);
    }

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

@Override
public void run() {
// TODO Auto-generated method stub

}
}

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...