更新时间:2021-10-07 06:39:13
该问题是在这里:
@Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// unregister listener
// sensorManager.unregisterListener(this);
}
你不注销侦听器,使其注册多次。
You're not unregistering the listener, so it is registered multiple times.
我知道你想要做的是继续听即使该活动被暂停,而你的可能的使用布尔标志,只能注册一次。但它可能不是一个好主意。 Activites不可见可以由系统在任何时候结束。
I understand that what you want to do is to keep listening even if the activity is paused, and you could use a boolean flag to only register once. But it's probably not a good idea. Activites that are not visible can be finished by the system at any time.
有关这些类型的用例服务
将更为合适的(作为奖励,你可以将它设置为启动对 BOOT_COMPLETED
,这样你就不需要重新运行应用程序,当你重新启动设备设置此监听器)。
For these kinds of use cases a Service
would be far more appropriate (as a bonus, you could set it up to start on BOOT_COMPLETED
, so that you don't need to re-run the app to set up this listener when you restart the device).
所以,总之,我会建议:
So, in short, I would recommend:
的onCreate()
,注册服务作为一个监听器的SensorManager
(非常多,你在这里做的)。意图
来启动服务(见的文档)。onCreate()
, register the service as a listener to SensorManager
(very much as you do here).Intent
to start the service (see docs).