Reputation: 1
I create one asynctask
class to download on file from web.
This is my class :
private class DownloadFile1 extends AsyncTask<String, Integer, String> {
private boolean done = false;
@Override
protected String doInBackground(String... sUrl) {
done = false;
if (isOnline() == true && sdmounted() == true) {
try {
URL url = new URL(sUrl[0]); // get url
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
// url[1]= file name
OutputStream out = (downloaded == 0) ? new FileOutputStream("/sdcard/Points.ir/" + sUrl[1])
: new FileOutputStream("/sdcard/Points.ir/"
+ sUrl[1], true);
OutputStream output = new BufferedOutputStream(out, 1024);
byte[] data = new byte[1024];
int count = 0;
while (done != true && isOnline() == true && (count = in.read(data, 0, 1024)) >= 0) {
output.write(data, 0, count);
downloaded += count;
}
output.flush();
output.close();
in.close();
} catch (Exception e) {
}
} else {
networkerror = 1;
}
return null;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress)
{
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
}
}
when I create a object of this class and Execute, every thing works fine . but when create 2 object and Execute for download 2 file at the same time it get FC ?? what do I ? (Sorry for my bad English Speaking)
Upvotes: 0
Views: 940
Reputation: 12900
AsyncTask's can only be executed 1 time. So once your AsyncTask is running, you cannot run it again. That's the reason why you have the String... param in the doInBackground method, that can be a list of Strings.
So, instead of creating two objects, you can use the following:
DownloadFile1 task = new DownloadFile1();
task.execute("url1", "url2", "url3"); // All these urls will be processed after each other
Than, in your AsyncTask doInBackground(), you can do something like:
@Override
protected String doInBackground(String... sUrl) {
done = false;
for(int i=0 ; i < sUrl.length ; i++){
if (isOnline() == true && sdmounted() == true) {
try {
String currentUrl = sUrl[i];
// continue with your code here, using currentUrl instead
// of using sUrl[0];
}
}
}
}
Upvotes: 1