2012-03-16 57 views
0

我是Android编程和线程的新手。我想从远程服务器获取图片并显示它。 (迄今为止的作品^^) 但图片来自相机,所以我需要一个新的,只要我展示我之前下载的一个。这意味着,线程永远不应该停止抓图片。 (只要活动存在。)
另外我只想建立到服务器的一个连接,然后只需执行HTTP-gets。所以我必须有一个Thread可以使用的参数“连接”。Android - 反复执行线程

为了得到一个想法 - 它应该工作是这样的(但显然事实并非如此):

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); 
    } 
} 

回答

0

可能会更好地使用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; 
} 
+0

谢谢,这帮了我很多! – user1271544 2012-03-16 13:08:59

+0

还有一件事情...没有'c.close();'我如何关闭'URLConnection'?到目前为止我已经找到了一些东西。 – user1271544 2012-03-16 13:21:53

+0

嗯,那么你应该得到'InputStream'上应该有'.close()'。你应该总是关闭你打开的东西 - 这就是为什么我添加了一个关闭:) – zapl 2012-03-16 13:44:44

0

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

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

嗨,现在我得到这个错误:无法执行任务。该任务已在运行。 – user1271544 2012-03-16 11:32:31

+0

也许尝试先取消任务。 – goodm 2012-03-16 11:37:06

0

异步任务只能执行一次会更好...... 任务只能执行一次(如果第二试图执行一个异常将被抛出。 ) 看到这个..上的AsyncTask documentation on AsyncTask 文档,我建议最好是,如果你使用的服务,下载... 甚至可以使用一个线程...

这样

public void run() { 
    while (true) { 
     //get image... 
    } 
}