问题
I was reading this tutorial on how to use a custom surface view class in an XML layout and when I ran the code, the app crashed when my phone's orientation changed. I've noticed a lot of examples involving custom threads and surface view subclasses crashing when the orientation changes, does anybody have any idea why this is happening?
09-25 18:19:40.639: E/Trace(4982): error opening trace file: No such file or directory (2)
09-25 18:19:40.639: D/ActivityThread(4982): setTargetHeapUtilization:0.25
09-25 18:19:40.639: D/ActivityThread(4982): setTargetHeapIdealFree:8388608
09-25 18:19:40.639: D/ActivityThread(4982): setTargetHeapConcurrentStart:2097152
09-25 18:19:40.959: D/libEGL(4982): loaded /system/lib/egl/libEGL_adreno200.so
09-25 18:19:40.979: D/libEGL(4982): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
09-25 18:19:40.979: D/libEGL(4982): loaded /system/lib/egl/libGLESv2_adreno200.so
09-25 18:19:41.049: I/Adreno200-EGLSUB(4982): <ConfigWindowMatch:2087>: Format RGBA_8888.
09-25 18:19:41.099: E/(4982): <s3dReadConfigFile:75>: Can't open file for reading
09-25 18:19:41.099: E/(4982): <s3dReadConfigFile:75>: Can't open file for reading
09-25 18:19:41.099: D/OpenGLRenderer(4982): Enabling debug mode 0
09-25 18:19:58.127: W/dalvikvm(4982): threadid=11: thread exiting with uncaught exception (group=0x40d46438)
09-25 18:19:58.147: E/AndroidRuntime(4982): FATAL EXCEPTION: Thread-156822
09-25 18:19:58.147: E/AndroidRuntime(4982): java.lang.NullPointerException
09-25 18:19:58.147: E/AndroidRuntime(4982): at com.example.practicesurface.MySurfaceView.onDraw(MySurfaceView.java:129)
09-25 18:19:58.147: E/AndroidRuntime(4982): at com.example.practicesurface.MySurfaceView$MySurfaceThread.run(MySurfaceView.java:39)
回答1:
move this line of code:
thread = new MySurfaceThread(getHolder(), this);
from the init() method in MySurfaceView, to the surfaceCreated() method.
When shifting orientation, the onCreate methods are recalled, but the constructor of MySurfaceView won't be called, since it is retained.
Hope this helps :)
来源:https://stackoverflow.com/questions/18994357/android-custom-surface-view-crashing-upon-orientation-change