ProximityActivity

 

public class ProximityActivity extends Activity implements SensorEventListener {

 

private static final String TAG = "ProximityActivity";
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.main);
Log.d(ProximityActivity.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(ProximityActivity.TAG, "registerListener...");
// 一定要在這註冊
this.mgr.registerListener(this, this.proximity,
SensorManager.SENSOR_DELAY_NORMAL);
}

 

@Override
protected void onPause() {
super.onPause();
Log.d(ProximityActivity.TAG, "unregisterListener...");
// 一定要在這解註冊
this.mgr.unregisterListener(this, this.proximity);
}

 

@Override
public void onSensorChanged(SensorEvent event) {
Log.d(ProximityActivity.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);
}
this.lastVal = thisVal;
}
String msg = "Current val: " + this.lastVal;
Log.d(ProximityActivity.TAG, msg);
}

 

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

 

記得振動要加上 android.permission.VIBRATE 這個許可權。

 

振動和距離感應器都要
安裝到手機上才會運作。
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()