Thread Handlers stop working on orientation change
I've got a Thread parsing XML in the background of my app. As it does so, it updates a progress bar in the activity's view via a Handler. This works fine until the phone changes orientation (and probably during other destructive actions, like multitasking, though I haven't throughly tested there). After any number of rotations, the progress bar freezes where it is and never progresses, even when the parsing is done and my ListView updates itself just fine.
Here's a cut-down version of the relevant code. I'm not including it here, but I do have code in plac开发者_JAVA百科e to make sure the thread is continuing unencumbered after the rotation--like I said, the parsing eventually finishes and updates the ListView in the same amount of time. It's just the progress bar handler that doesn't work:
private ProgressBar mProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory_list);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
mProgress.setMax(entryCount);
startXMLParseThread();
}
private void startXMLParseThread() {
new Thread () {
Handler hUpdateProgressBar = new Handler(){
public void handleMessage(Message msg) {
mProgress.setProgress(entryCount);
}
};
public void run() {
while (parserEvent != XmlPullParser.END_DOCUMENT) {
entryCount++;
hUpdateProgressBar.sendEmptyMessage(0);
parserEvent = parser.next();
}
mHandler.post(new Runnable() {
public void run() {
adapter.getCursor().requery();
}
});
}
}.start();
}
May be its running the onCreate method again on orientation change ...so it loses reference to previous handler...try this ..add attribute to the manifest file in that particular activity android:configChanges="orientation"...in this way it wont run onCreate again...give it a shot...
精彩评论