【问题标题】:use of asynctask inside asynctask在 asynctask 中使用 asynctask
【发布时间】:2011-07-18 11:02:47
【问题描述】:

我想使用 AsyncTask 将图像加载到 ListView。

private class LoadImageTask extends AsyncTask<HashMap<String,Bitmap>,Void,Bitmap>{

    @SuppressWarnings("unchecked")
    @Override
    protected void onPostExecute(Bitmap result) {

               if(model.getIconCache().get(cellIcon)!=null){
                   icon.setImageBitmap(model.getIconCache().get(cellIcon));
                }else{
                    new LoadImageTask().execute(model.getIconCache());

                }


    }

    @Override
    protected Bitmap doInBackground(HashMap<String, Bitmap>... params) {
        //return model.getIconCache().get(cellIcon);
        return null;

    }

}

好的,我知道这不是情感代码。然而它运作良好,但有很多内存分配。在阅读有关 AsyncTask 的文档时,它说 Asynctask 只能从 UI 线程调用,它怎么能让它在自身内部使用?当然,我想让我的代码在单个 AsyncTask 中工作。代码中的“模型”是在运行时通过另一个线程更新的对象。所以我需要找到一种方法来使用单个 Asynctask 并定期控制对象的状态。我怎么做?谢谢

【问题讨论】:

    标签: android multithreading listview asynchronous android-asynctask


    【解决方案1】:

    仅在后台线程上运行,postExecute 和 preExecute 在 UI 线程本身上运行。出于同样的原因,您可以在其中显示和关闭对话框。

    如果您想将单个 Asynctask 用于多个目的,您可以通过在 .execute() 方法中传递不同的常量来玩弄..

    我的意思是这样的。

    Integer Constant1 = 1;
    int Constant2 = 2;
    

    在调用时,

    new Background.execute(Constan1 or 2)
    

    在 AsyncTask 中

    doInBackground(Object.. arg0)
    {
    if(arg0.equals())
    {
    
    }
    else if(arg0.equals())
    {
    }
    }
    

    【讨论】:

      【解决方案2】:

      查看 asynctask 文档:http://developer.android.com/reference/android/os/AsyncTask.html

      private class MyTask extends AsyncTask<Void, Integer, Boolean> {
      
           protected Boolean doInBackground(Void...) {
               int i = 0;
               while(true){
                   publishProgress(i++);
               } 
           }
      
           protected void onProgressUpdate(Integer... progress) {
               myObject.setState(progress[0]);
           }
       }
      

      您在 doInBackground 方法(在后台线程中运行)中执行您的后台工作。

      您在 onProgressUpdate(在 ui 线程上运行)中控制对象的状态

      您使用 publishProgress 在后台线程和 ui 线程之间发送消息。这些消息可能包含您的对象的状态。

      【讨论】:

        猜你喜欢
        • 2018-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-22
        • 2018-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多