Skip to content Skip to sidebar Skip to footer

Seems Like My Little Android App Is Running Multiple Instance

I know this is very lame but I'm totally new to android development. I'm writing a sensor based app which will change wallpaper each time the phone is shaked. Once the app is minim

Solution 1:

The problem is here:

@OverrideprotectedvoidonResume() {
    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);
  }

  @OverrideprotectedvoidonPause() {
    // unregister listener// sensorManager.unregisterListener(this);
  }

You're not unregistering the listener, so it is registered multiple times.

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.

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:

  • 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.

Post a Comment for "Seems Like My Little Android App Is Running Multiple Instance"