你好我怎么能在一个单独的线程中编写这个代码,因为我在我的主线程中有一个密集的操作。所以我必须使用Async Activity并将网络密集型操作委托给'doInBackground'方法。但我不知道知道如何编辑
public void setImage(ImageView aView, final URL aURL) throws IOException {
final Bitmap bm = null;
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
URLConnection conn = null;
try {
conn = aURL.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
conn.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream is = null;
try {
is = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Bufferisation pour le t�l�chargement
BufferedInputStream bis = new BufferedInputStream(is, 8192);
// Cr�ation de l'image depuis le flux des donn�es entrant
bm = BitmapFactory.decodeStream(bis);
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
};
task.execute(null, null, null);
// Fixe l'image sur le composant ImageView
aView.setImageBitmap(bm);
}
请帮助我谢谢
答案 0 :(得分:0)
试试这个
public void setImage(ImageView aView, URL aURL) {
try {
Bitmap bm;
AsyncTask<URL, Void, Bitmap> task = new AsyncTask<URL, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(URL... params) {
URLConnection conn = params[0].openConnection();
conn.connect();
InputStream is = conn.getInputStream();
// Bufferisation pour le t�l�chargement
BufferedInputStream bis = new BufferedInputStream(is, 8192);
// Cr�ation de l'image depuis le flux des donn�es entrant
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
};
bm = task.execute(aURL, null, null).get();
// Fixe l'image sur le composant ImageView
aView.setImageBitmap(bm);
} catch (IOException e) {
aView.setImageDrawable(mNoImage);
Log.e("DVP Gallery",
"Erreur t�l�chargement image URL : " + aURL.toString());
e.printStackTrace();
}
}
答案 1 :(得分:0)
根据AsyncTask的文档,您可以使用以下内容:
class param{
ImageView iv;
URL aURL;
}
private class MyAsyncTask extends AsyncTask<param, Void, Void> {
protected Void doInBackground(param... p) {
int count = p.length;
for (int i = 0; i < count; i++) {
// your operations using p.iv and p.aURL
}
}
}
然后你可以回想起它传递了你需要的所有参数:
new MyAsyncTask().execute(param1, param2, param3);