I'm launching a thread that shows a dialog, and if i press the back key (to do some logic to stop the thread), the onKeyDown listener of the activity is not being called. It is because it is being catched by the thread with the dialog... How can i avoid that?
this is my code:
public static void getRemoteImage(final String url, final Handler handler) {
Thread thread = new Thread(){
public void run() {
try {
Looper.prepare();
handler.sendEmptyMessage(Util.SHOW_DIALOG);
final URL aURL = new URL(url);
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
image = BitmapFactory.decodeStream(bis);
bis.close();
handler.sendEmptyMessage(Util.HIDE_DIALOG);
Looper.loop();
}catch (Exception e) {e.printStackTrace();}
}
};
thread.start();
}
If you make your dialog cancelable, you can use this code in your activity.
Then you don't have to use onKeyDownListener
at all. The back button automatically calls the onCancel()
method.
The onCreateDialog
code would look something like this then:
updatingDialog = new ProgressDialog(this);
updatingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
updatingDialog.setMessage(getString(R.string.busy));
updatingDialog.setCancelable(true);
updatingDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
thread.interrupt();
}
});
Appearantly, the decodeStream
method cannot be interrupted easily (see comments). More information here:
SO answer