Search code examples
androidandroid-sensors

How to handle a sensor monitoring during screen orientation change?


In my activity, i monitor a sensor, with "onSensorChanged" method.

I start monitoring the sensor when a button in that activity is pushed (in the "onClick" method).

I register and unregister the listening in the onPause and onResume methods.

Here is the code:

public void onCreate(Bundle savedInstanceState) {
  //Here i set "mySensor"
}

public void onClick(View view){
  sensorManager.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_FASTEST);
}

protected void onPause() {
  sensorManager.unregisterListener(this, mySensor);
}

protected void onResume() {
  sensorManager.registerListener(this, mySensor, SensorManager.SENSOR_DELAY_FASTEST);
}

public final void onSensorChanged(SensorEvent event) {
  //do things
}

The problem is that, when there is an screen orientation change, the monitoring stops, the things i do within "onSensorChanged" stop until i press the button again.

I have been reading, and it seems that when the screen orientation changes, my activity is destroyed and recreated, but i would like the monitoring of the sensor not stopping during that process.

How can i keep the monitoring? i think it must be done using the Bundle, but im not sure.

Thanx.


Solution

  • You have a few choices:

    1. You can move your sensor listener into your application class, defined by android:name in <application> in your manifest. See here, naming a class that you've derived from android.app.Application. I would recommend this approach.

    2. You can add android:configChanges="orientation" to your activity manifest but, as described here, you'll need to handle the reloading of appropriate resources, such as orientation specific layout, in the onConfigurationChanged() of your activity. I wouldn't recommend this as you would still have the issue of the monitoring disappearing when the other configuration changes occur or you will need to work out how your application should handle them (and add them to the list of changes in android:configChanges).

    3. Disabled orientation changes entirely for your application by using android:screenOrientation as described here, but I really wouldn't recommend this unless there are other reasons why you want your application to only work in a certain orientation.