As we all know, there are many advantages of static variables: they can save global data. However, this may cause hidden bugs.
Situation:
I have my personal experience when developing a project. The following BUG was found for a long time. A project developed by multiple people. A colleague used static to pre-Cache some list data for the next interface. This data saves some image references, and these images are saved separately in another list, but the images are Recycle when they exit the program.
Symptom:
Occasionally, the recycled images are used in the program.
Java. lang. RuntimeException: Canvas: trying to use a recycled bitmap android. graphics. Bitmap
Analysis:
Due to the Android architecture design, static data is not cleared immediately when the program exits. In the above case, it can be found that when loading network data in advance is slow, and then enter the next interface, it is found that the static variable has data. At this time, this data is the data when the program exits, but the image referenced by this data has been recycled. This causes the previous phenomenon.
Solution:
When you exit the program, the data in the static variable is cleared.
Suggestion:
In the development process, try to use less static data, and try to concentrate static variables in a class. (For reference only)
Extension:
When Android exits the program, it does not verify that static data is cleared immediately.
Public class TestStatic {
Private static int nValue = 0;
Static {
NValue ++ = 100;
}
Public TestStatic (){
NValue ++ = 300;
Log. I ("TestStatic", "nValue:" + nValue );
}
}
Result:
05-09 11:15:04. 589: I/TestStatic (8093): nValue: 400
05-09 11:15:08. 309: I/TestStatic (8093): nValue: 700
When the program is started for the first time, the static code is executed before TestStatic ();
When you enter the program for the second time, directly execute TestStatic () and skip the static code;