我正在构建一个使用Power Button计数来执行某些操作的应用程序,我有一个BroadcastReceiver和一个帮助我这样做的服务。我使用ACTION_SCREEN_OFF,ACTION_SCREEN_ON和ACTION_USER_PRESENT作为意图过滤器,一切正常,每次按下的电源按钮都执行我想要的操作,但是接近传感器确实可以使用与ACTION_SCREEN_OFF和ACTION_SCREEN_ON相同的场景。因此,当用户拨打电话并且我的服务在后台运行时检查ACTION_SCREEN_OFF和ACTION_SCREEN_ON,以便当呼叫者将设备带离他/她的耳朵时,接近传感器执行相同的操作。我想在这里区分Power Button press和Proximity sensor动作。为了完成这项工作,我应该遵循什么?以下是我的代码的一部分,可能有助于您理解我想要问的内容。
我的类扩展服务在其onCreate()中包含以下代码:
mReceiver=new PowerButtonActionReciever();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
registerReceiver(mReceiver, filter);
类扩展BroadcastReceiver捕获电源按钮单击其onReceive()方法:
@Override
public void onReceive(Context context, Intent intent)
{
//perform some action
}
答案 0 :(得分:0)
您可以为接近传感器注册一个监听器,并执行与电话应用程序相同的检查。
private SensorManager mSensorManager;
private Sensor mSensor;
...
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
public class SensorActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mProximity;
@Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get an instance of the sensor service, and use that to get an instance of
// a particular sensor.
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mProximity = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
}
@Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
float distance = event.values[0];
// Do something with this sensor data.
}
@Override
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
mSensorManager.registerListener(this, mProximity, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// Be sure to unregister the sensor when the activity pauses.
super.onPause();
mSensorManager.unregisterListener(this);
}
}