首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android -重复执行线程

Android -重复执行线程
EN

Stack Overflow用户
提问于 2012-03-16 19:08:08
回答 3查看 840关注 0票数 0

我是Android编程和线程的新手。我想从远程服务器获取一张图片并显示它。(到目前为止可以用^^)但是照片是从相机拍的,所以我需要一张新的,只要我展示我之前下载的那张。这意味着,线程永远不会停止抓取图片。(只要活动存在。)

此外,我只想建立一个连接到服务器,然后只做HTTP-gets。所以我必须有一个Thread可以使用的参数"connection“。

为了得到一个想法-它应该是这样工作的(但显然它不是):

代码语言:javascript
复制
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);
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-16 19:23:02

在这里使用Thread可能更好,因为AsyncTask用于任务在某一时刻结束的时间。像下面这样的东西可以为你工作。除此之外,您可以更好地使用本地Service

代码语言:javascript
复制
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;
}
票数 0
EN

Stack Overflow用户

发布于 2012-03-16 19:18:02

你应该为它设置一些延迟,但是为了解决这个问题,我认为它应该是这样的:

代码语言:javascript
复制
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("...");
}
}
票数 0
EN

Stack Overflow用户

发布于 2012-03-16 19:25:29

异步任务只能执行一次...该任务只能执行一次(如果尝试第二次执行,将抛出异常)。看看这个。关于AsyncTask documentation on AsyncTask 的文档我建议您最好使用服务来下载...或者甚至可以使用线程..。

像这样

代码语言:javascript
复制
 public void run() {
    while (true) {
        //get image...
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9736172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档