我正在构建一个小应用程序,我需要检测设备的运动,只有当它在我的手中而不是在它的口袋里时。
现在,我构建了应用程序,但是当我走路或跑步时,传感器事件会被触发,而移动设备会放在口袋里?
当有人拿着设备时,是否仍然调用传感器?
谢谢, 拉梅什
答案 0 :(得分:0)
您可以使用ACTION_USER_PRESENT意图首先检查手机是否正在使用或处于待机状态。之后,您可以实施Accelerometer来检测动作。这是一个例子:
public class SensorsActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sensors);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
// check sensor type
if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){
// TODO after accelerometer detected do something here
}
}
}
对于ACTION_USER_PRESENT检测,您需要BroadcastReceiver,其中包含:
public class SensorReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_USER_PRESENT)) {
// TODO notify the user is present
}
}
}
并在 Manifest.xml 中声明它:
<receiver android:name=".SensorReceiver">
<intent-filter android:enabled="true" android:exported="false">
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
希望它有所帮助!