0

Button song,pdf,image,doc;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initViews();
    setListeners();
}
private void initViews(){
    song = (Button) findViewById(R.id.song_download);
    pdf = (Button) findViewById(R.id.pdf_download);
    image = (Button) findViewById(R.id.image_download);
    doc = (Button) findViewById(R.id.text_download);
}
private void setListeners() {
    song.setOnClickListener(this);
    pdf.setOnClickListener(this);
    doc.setOnClickListener(this);
}
@Override
public void onClick(View v) {

    Intent intent ;
    switch (v.getId()){
        case R.id.song_download:
             intent = new Intent(MainActivity.this,DownloadTask.class);
            intent.putExtra("song",Utils.downloadMp3Url);
            intent.putExtra("filename","mysong.mp3");
              intent.putExtra("btnsong","btnsong");
            startActivity(intent);
            break;
        case R.id. pdf_download:
             intent = new Intent(MainActivity.this,DownloadTask.class);
            intent.putExtra("pdf",Utils.downloadPdfUrl);
            intent.putExtra("filename2","mybook.pdf");
              intent.putExtra("btnpdf","btnpdf");
            startActivity(intent);
    }


}

DownloadTask class public class DownloadTask extends AppCompatActivity {

public Context context;
public String url;
public String downloadUrl;
public String downloadFileName;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);

    Intent intent = getIntent();
    //Intent intent2 = getIntent();
 String  s=intent.getStringExtra("song");
   String k = intent.getStringExtra("pdf");



}



private class DownloadingTask extends AsyncTask<String,Integer,String>{

 //   int progressStatus =0;

    File apkStorage = null;
    File outputFile = null;

   // LayoutInflater inflater;
   // Button pause;
  //  ProgressBar bar;

    @Override
    protected void onPreExecute() {

       progressBar = (ProgressBar) findViewById(R.id.progress);
        progressBar.setMax(100);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            URL downloadUrl = new URL(url);
            HttpURLConnection c = (HttpURLConnection) downloadUrl.openConnection();



            c.setRequestMethod("GET");

            if(new CheckForSdCard().isSDCardPresent()){
                apkStorage = new File(Environment.getExternalStorageDirectory()+"/"+Utils.downloadDirectory);

            }
            else {
                Toast.makeText(context,"There's no SD card",Toast.LENGTH_SHORT).show();
            }
            if(!apkStorage.exists()){
                apkStorage.mkdir();
            }
            outputFile = new File(apkStorage,downloadFileName);
            if(!outputFile.exists()){
                outputFile.createNewFile();
            }
            FileOutputStream outputStream  = new FileOutputStream(outputFile);
            int lenghtOfFile = c.getContentLength();
            InputStream is = (InputStream) c.getContent();
          //  int buffersize = (int)Math.ceil(lenghtOfFile/(double)100);
            byte[] buffer = new byte[1024];
            int length = 0;
            long total = 0;
           while((length=is.read(buffer))!=-1){
               total+=length;
               publishProgress((int)((total*100)/lenghtOfFile));
               outputStream.write(buffer,0,length);
             // publishProgress(i);


            }
        /* for(int i =1;i<100;i++){
             int read = is.read(buffer,0,length);
             outputStream.write(buffer,0,length);
             total+=read;
             publishProgress(i);
         } */

            outputStream.close();
            is.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "Download Complete";
    }

    @Override
    protected void onProgressUpdate(Integer... values) {

        progressBar.setProgress(values[0]);



    }

    @Override
    protected void onPostExecute(String result) {


      //  Toast.makeText(context, result,Toast.LENGTH_SHORT).show();
    }
}

}

I am building an app that has 2 buttons. one for downloading a song and another for downloading a pdf file. When I click one button the download progress is shown in another activity Now I want to download them in parallel. I have a asynctask class. I want to download them both in parallel using the same asynctask class.

Inan Mahmud
  • 226
  • 3
  • 14
  • 1
    Create 2 instances of your AsyncTask and provide the data url you want to download – Mohammed Rampurawala Nov 02 '17 at 06:20
  • Using the example in here: https://developer.android.com/reference/android/os/AsyncTask.html `new DownloadFilesTask().execute(url1, url2, url3);` or `foo = new DownloadFilesTask()` then `foo.execute(url1, url2, url3);foo.execute(url4, url5, url6);` (if you really need two calls) –  Nov 02 '17 at 06:21
  • @mzeus.bolt I've created 2 instances of my asynctask class but it still isn't working. – Inan Mahmud Nov 02 '17 at 06:34
  • `Toast.makeText(context,"There's no SD card",Toast....`. You cannot display a Toast in the doInBackground of an AsyncTask. Your app will crash. Moreover you continue with your code as if the card is present. No good. You should stop then. – greenapps Nov 02 '17 at 08:39
  • `apkStorage.mkdir();`. Check the return value as it might fail to create the directory. In that case do NOT continue but stop. – greenapps Nov 02 '17 at 08:41
  • `if(!outputFile.exists()){ outputFile.createNewFile(); }`. Remove that. The file will be created by the new FileOutputStream(). – greenapps Nov 02 '17 at 08:42
  • `catch (IOException e) { e.printStackTrace(); } return "Download Complete";`. Even if there is an exception you shout download complete. Very wrong. – greenapps Nov 02 '17 at 08:47

2 Answers2

0

As your code is given, You are starting AsyncTask with Intent. That is wrong.

You need to check AsyncTask implementation.

How to pass parameters and objects in AsyncTask

Mohammed Rampurawala
  • 3,033
  • 2
  • 22
  • 32
0

Your AsyncTask class is for downloading one file.

You can instantiate two instances of your class to download two files but they will be executed not in parallel but after each other.

If you want to use them in parallel start them with executeOnExecutor().

greenapps
  • 11,154
  • 2
  • 16
  • 19