我有一种从互联网下载图像并将其存储在位图上的方法。在下载图像时,它会显示一个加载对话框。该方法工作正常,但我想将功能添加到我的应用程序中以停止线程(因此停止下载)并在用户按下手机上的返回键时关闭对话框。
public static void getRemoteImage(final String url, final Handler handler) {
Thread thread = new Thread(){
public void run() {
try {
Looper.prepare();
handler.sendEmptyMessage(Util.SHOW_LOADING_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_LOADING_DIALOG);
Looper.loop();
}catch (Exception e) {e.printStackTrace();}
}
};
thread.start();
}
当用户在我的活动上按后退键时,如何添加停止线程的功能?我在谷歌上找不到路
编辑:这是我尝试使用 Ovidiu 答案,但它不起作用:(
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialogHandler.sendEmptyMessage(Util.HIDE_DIALOG);
task.cancel(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
private class DownloadTask extends AsyncTask{
@Override
protected void onPreExecute() {
super.onPreExecute();
//INITIALIZATIONS
}
@Override
protected Object doInBackground(Object... params) {
try {
dialogHandler.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();
dialogHandler.sendEmptyMessage(Util.HIDE_DIALOG);
}catch (Exception e) {e.printStackTrace();}
return null;
}
@Override
protected void onCancelled(){
super.onCancelled();
System.out.println("Task cancelled");
}
}