Nexus 5 going to sleep mode makes activity life cycle buggy

给你一囗甜甜゛ 提交于 2019-12-04 10:07:50

So the bug was due to orientation change... but not really. In fact it's not "orientation" changed (in my case) but "screenSize changed" that is fired as a configurationChange event when the Nexus 5 go to sleep mode and when your activity is in Portrait. It's not happening on Nexus 7 because its normal mode is landscape when going to sleep so no configurationChange is fired.

Solution
It means, after HoneyComb (because screenSize has begun to be used by HC), that if, in your manifest, your are using the

 android:screenOrientation="landscape"

You also need to had the following this line to your manifest:

 android:configChanges="orientation|screenSize"

And in your MotherActivity (the one inherits by your activities) or in your activities, you have to overwrite the configuration change method, that way:

 /*
 * (non-Javadoc)
 * @see android.app.Activity#onConfigurationChanged(android.content.res.Configuration)
 */
@Override
public void onConfigurationChanged(Configuration newConfig) {
    Log.e("MotherActivity", "onConfigurationChanged called ");
    // this method is there to ensure no configuration changes when going to sleep mode
    // because the device wants my app to go on portrait and then fire screenSize changes
    // sometime some montainview code sucks
    super.onConfigurationChanged(newConfig);
    // and of course do nothing !!!
}

Can have a look here for a better understanding of the onConfigurationChange and how to handle it.@http://developer.android.com/guide/topics/resources/runtime-changes.html

Back to my problem
In my case, i was fighting with lost threads due to that not expected configuration changes.
Simple trick n°1
So a simple trick to avoid such a pain and to detect it quickly, is to add Log to your Mother activity in dev mode. So when testing you always have the log of your activities' life cycle. And it will help you avoiding life cycle mess.
Exemple:

/*
 * (non-Javadoc)
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.e("MotherActivity", "onCreate called");
    super.onCreate(savedInstanceState);
}

Threads law
And finally, always, i mean ALWAYS, have a deep look at your threads (if you have any) and insure there is no memory leak (threads must die) and also insure your threads are retained (onRetainNonConfigurationInstance or using a fragment without GUI and setRetainInstance(true)) when configuration changes or insures to handle configurations changes.
Simple trick n°2
Another trick is also listen for mcc and mnc (in your manifest android:configChanges="orientation|screenSize|mcc|mcn"), because your application most of the time doesn't care about changing telecom operator. And most of the time you did not test that case.

Have a nice day to you all!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!