Thread makes activity crush while rotating
I've got an activity that uses a thread in order to read a some content from a file.
The problem is that if the user decides to rotate the screen while the thread is running the application crushes. I know that I can prevent the screen from rotating 开发者_如何学Gousing:android:screenOrientation="portrait"
But what I want to do is to stop the thread from running so the application can restart safely or prevent the activity from restarting.
You can use an asynctask and stop it on the Activity.onPause() method.
On an important side node, setting the property android:screenOrientation="portrait"
won't stop android from destroying and recreating the screen on a change of the orientation, it will just don't display a landscape mode.
You have to add this to the activity declaration in the manifest:
android:configChanges="keyboardHidden|orientation|screenSize"
Is your thread holding references to UI objects like buttons? If so, because the rotation destroys and recreates the activity, you'll be referencing the old objects, not the new ones. That's why it's necessary to destroy and recreate the thread or asynctask.
When user rotates the device, your application is restarted in that process the method onDestroy is called. So you can use Activity.onDestroy method to destroy/stop your thread.
http://developer.android.com/reference/java/lang/Thread.html there you can find stop, destroy, interrumpt and other methods, not sure what of them should be used right now.
精彩评论