How can I find out if the MainActivity is being paused from my Java class?
Posted
by
quinestor
on Stack Overflow
See other posts from Stack Overflow
or by quinestor
Published on 2012-10-28T10:31:21Z
Indexed on
2012/10/28
11:01 UTC
Read the original article
Hit count: 223
I am using motion sensor detection in my application.
My design is this: a class gets the sensor services references from the main activity and then it implements SensorEventListener. That is, the MainActivity does not listen for sensor event changes:
public void onCreate(Bundle savedInstanceState) {
// ... code
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// The following is my java class, it does not extends any android fragment/activty
mShakeUtil = new ShakeUtil(mSensorManager,mAccelerometer,this);
// ..more code..
}
I can't redesign ShakeUtil so it is a fragment nor activity, unfortunately. Now to illustrate the problem consider:
- MainActivity is on its way to be destroyed/paused. I.e screen rotation
- ShakeUtil's onSensorChanged(SensorEvent event) gets called in the process..
One of the things that happen inside onSensorChanged is a dialog interaction, which gives the error:
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
When the previous happens between MainActivity's onSaveInstanceState and onPause. I know this can be prevented if I successfully detect that MainActivity is being pause in ShakeUtil.
How can I detect that MainActivity is being paused or onSaveInstanceState was called from ShakeUtil?
Alternatively, how can I avoid this issue without making Shakeutil extend activity?
So far I have tried with flag variables but that isn't good enough, I guess these are not atomic operations. I tried using Activity's isChangingConfigurations(), but I get an undocummented "NoSuchMethodFound" error.. I am unregistering the sensors by calling ShakeUtil when onPause in main ACtivity
© Stack Overflow or respective owner