且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

好像我的小Android应用程序上运行多个实例

更新时间: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 (非常多,你在这里做的)。

  • 当你的活动运行,发送意图来启动服务(见的文档)。

  • (可选),从而使服务重新启动设备重新启动时,指定ACTION_BOOT_COMPLETED的监听器。请参见这个答案

  • Create a Service. In onCreate(), register the service as a listener to SensorManager (very much as you do here).
  • When your activity runs, send an Intent to start the service (see docs).
  • Optionally, specify a listener for ACTION_BOOT_COMPLETED so that the service is restarted when the device restarts. See this answer.