使用for循环for asynctask

时间:2014-06-09 17:33:46

标签: java android

我有一个发送请求并接收图像的asyntask。它适用于1项,事情就在这里我有这个方法:

  Arraylist<String> todownload;
   .
   .

    public void downloadit(){


    int size=todownload.size();
     for (int i=0;i<size;i++) {
          this.todo=todownload.get(i);
            System.out.println("Dowloading = " + todo);
    MyAsyncImagesDownload sync = new MyAsyncImagesDownload();
 System.out.println("Size="+todownload.size());
    sync.execute();

     }

使其可以下载超过1个请求。但是请说todownload里面有2个值,todo的值是Async使用的那个,在服务器上总是最后一个,我也试着用以下代码替换for循环:

for(String todo:Todownload)
.
.

还是一样的。所以我觉得循环在执行作业完成之前完成了它的工作,所以我在执行和Notifyall()之后添加了Wait方法到异步任务结束,但似乎我得到了一些错误。你能帮我解决一下我能做些什么来实现这个目标吗?感谢

异步代码是:

BufferedOutputStream bos;  
    OutputStream output;  
    DataOutputStream dos; 
    int len;  
    int smblen;   
    InputStream in;  
    DataInputStream clientData; 
    FileOutputStream fos; 
    String filepath;
    String target;
    Socket clientSocket;




     @Override
     protected String doInBackground(String... Result) {
        // TODO Auto-generated method stub



String REresponse = null; 


Log.i("lifemate","im here in the Async !");
try {
    socket = new Socket(server, 1450);
} catch (UnknownHostException e5) {
    // TODO Auto-generated catch block
    e5.printStackTrace();
} catch (IOException e5) {
    // TODO Auto-generated catch block
    e5.printStackTrace();
}

String msg = "Connection accepted " + socket.getInetAddress() + ":" +    
 socket.getPort();
  Log.i(LOGTAG, msg);

   try {
    sInput  = new ObjectInputStream(socket.getInputStream());
} catch (StreamCorruptedException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
} catch (IOException e4) {
    // TODO Auto-generated catch block
    e4.printStackTrace();
}
try {
    sOutput = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e3) {
    // TODO Auto-generated catch block
    e3.printStackTrace();
}

try {


sOutput.writeObject(todo);

received=false;

} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
 }

try {
sOutput.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
    //Log.i(LOGTAG,"this"+rdytosplit);

while(received==false)
{



 clientSocket = socket;

try {
in = clientSocket.getInputStream();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} 

clientData = new DataInputStream(in); //used    
// clientBuff = new BufferedInputStream(in); //use    
System.out.println("i have started");

int N=1;
while(N==1){    

   System.out.println("Starting...");    




           int fileSize = 0;
            try {
                fileSize = clientData.read();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }        
           fileSize = (fileSize > 0) ? fileSize :0; 
                                                                       // guard  
 against  
 negatives.
           List<File> files = new ArrayList<>(fileSize);          //store list of 
 filename from client directory        // Using List and <>
           List<Integer> sizes = new ArrayList<>(fileSize);       //store file size   
 from client 
         //Start to accept those filename from server

           for (int count=0;count < fileSize;count ++){  
               File ff = null;
                try {
                    ff = new File(clientData.readUTF());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }  
               files.add(ff);  
               filepath="storage/sdcard/Pictures/";




           }  

   for (int count=0;count < fileSize;count ++){  

           try {
                sizes.add(clientData.readInt());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
   }  

  for (int count =0;count < fileSize ;count ++){     

     len=sizes.get(count);  

   System.out.println("File Size ="+len);  



   try {
        output = new FileOutputStream(filepath + files.get(count));
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }  
   dos=new DataOutputStream(output);  
   bos=new BufferedOutputStream(output);  

   byte[] buffer = new byte[1024];    

   try {
        bos.write(buffer, 0, buffer.length);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } //This line is important  

   try {
        while (len > 0 && (smblen = clientData.read(buffer)) > 0) {   
            try {
                dos.write(buffer, 0, smblen);
            ////here you must add +1 value to imagechange_1 or ..._2
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
              len = len - smblen;  
              try {
                dos.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  

        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }    
   Log.i("downloader","job is done");
   N=2;

   try {
    dos.close();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
   //// should i close in and clientdata now ?
  }



}   //end loop 
received=true;
}






try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Run=false;
disconnect();

return REresponse;

     }

}

1 个答案:

答案 0 :(得分:0)

为什么不在looping内执行asynctask而不是循环asynctask

private class MyAsyncImagesDownload extends AsyncTask<URL, Integer, Long> {
    protected Long doInBackground(URL... urls) {
        int count = urls.length;
        long totalSize = 0;

        //a loop can be like this
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int) ((i / (float) count) * 100));
            if (isCancelled()) break;
        }
        return totalSize;
    }


    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}