2011年9月23日星期五

接近傳感器 (Proximity Sensor)

通過接近傳感器 (Proximity Sensor)可以檢測到 Android 手機靠近我的臉, 進而做一些動作, 例如禁用觸摸功能,或關閉屏幕.

public class AndroidProximitySensorActivity extends Activity {
/** Called when the activity is first created. */

SensorManager mySensorManager;
Sensor myProximitySensor;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mySensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
myProximitySensor = mySensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);

if (myProximitySensor == null){
//No Proximity Sensor!

}else{
mySensorManager.registerListener(proximitySensorEventListener, myProximitySensor,SensorManager.SENSOR_DELAY_NORMAL);
}
}

SensorEventListener proximitySensorEventListener = new SensorEventListener(){

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub

if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
//do something
}
}
};
}



沒有留言:

發佈留言