我是Android编程和线程的新手。我想从远程服务器获取一张图片并显示它。(到目前为止可以用^^)但是照片是从相机拍的,所以我需要一张新的,只要我展示我之前下载的那张。这意味着,线程永远不会停止抓取图片。(只要活动存在。)
此外,我只想建立一个连接到服务器,然后只做HTTP-gets。所以我必须有一个Thread可以使用的参数"connection“。
为了得到一个想法-它应该是这样工作的(但显然它不是):
private class DownloadImageTask extends AsyncTask<URLConnection, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
private URLConnection connection = null;
protected Bitmap doInBackground(URLConnection...connection ) {
this.connection = connection[0];
return getImageFromServer(connection[0]);
}
protected void onPostExecute(Bitmap result) {
pic.setImageBitmap(result);
this.doInBackground(connection);
}
}发布于 2012-03-16 19:23:02
在这里使用Thread可能更好,因为AsyncTask用于任务在某一时刻结束的时间。像下面这样的东西可以为你工作。除此之外,您可以更好地使用本地Service
protected volatile boolean keepRunning = true;
private Runnable r = new Runnable() {
public void run() {
// methods are a bit bogus but it should you give an idea.
UrlConnection c = createNewUrlConnection();
while (keepRunning) {
Bitmap result = getImageFromServer(c);
// that probably needs to be wrapped in runOnUiThread()
pic.setImageBitmap(result);
}
c.close();
}
};
private Thread t = null;
onResume() {
keepRunning = true;
t = new Thread(r);
t.start();
}
onPause() {
keepRunning = false;
t = null;
}发布于 2012-03-16 19:18:02
你应该为它设置一些延迟,但是为了解决这个问题,我认为它应该是这样的:
private class DownloadImageTask extends AsyncTask<URLConnection, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
private URLConnection connection = null;
protected Bitmap doInBackground(URLConnection...connection ) {
this.connection = connection[0];
return getImageFromServer(connection[0]);
}
protected void onPostExecute(Bitmap result) {
pic.setImageBitmap(result);
this.execute("...");
}
}发布于 2012-03-16 19:25:29
异步任务只能执行一次...该任务只能执行一次(如果尝试第二次执行,将抛出异常)。看看这个。关于AsyncTask documentation on AsyncTask 的文档我建议您最好使用服务来下载...或者甚至可以使用线程..。
像这样
public void run() {
while (true) {
//get image...
}
}https://stackoverflow.com/questions/9736172
复制相似问题