Proximity Sensor結合Vibrator

1. ProximityActivity.java

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.app.Activity;

public class ProximityActivity extends Activity {

    private Vibrator vibrator;
    private SensorManager proximitySensor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_proximity);
        initObject();
    }

    public void initObject() {
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        proximitySensor = (SensorManager) getSystemService(SENSOR_SERVICE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        proximitySensor.registerListener(proximityListener,
                proximitySensor.getDefaultSensor(Sensor.TYPE_PROXIMITY),
                SensorManager.SENSOR_DELAY_UI);
    }

    SensorEventListener proximityListener = new SensorEventListener() {

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

        }

        @Override
        public void onSensorChanged(SensorEvent event) {

            if (event.values[0] == event.accuracy) {
                long[] pattern = { 0, 1000 };
                vibrator.vibrate(pattern, 0);
            } else {
                vibrator.cancel();
            }
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        proximitySensor.unregisterListener(proximityListener);
    }
}

2. activity_proximity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ProximityActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Please near proximity sensor"
        android:textColor="@android:color/black"
        android:textSize="20dp" />

</RelativeLayout>

3. AndroidManifest.xml(重點程式碼)

<uses-permission android:name="android.permission.VIBRATE"/>

沒有留言: