【问题标题】:how can I download two different files in parallel using same asynctask class?如何使用相同的 asynctask 类并行下载两个不同的文件?
【发布时间】:2018-04-14 14:14:12
【问题描述】:

按钮歌曲,pdf,图片,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 类 公共类 DownloadTask 扩展 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();
    }
}

}

我正在构建一个有 2 个按钮的应用程序。一个用于下载歌曲,另一个用于下载 pdf 文件。当我单击一个按钮时,下载进度显示在另一个活动中现在我想并行下载它们。我有一个 asynctask 类。我想使用相同的 asynctask 类并行下载它们。

【问题讨论】:

  • 创建 2 个 AsyncTask 实例并提供要下载的数据 url
  • 使用此处的示例:developer.android.com/reference/android/os/AsyncTask.html new DownloadFilesTask().execute(url1, url2, url3);foo = new DownloadFilesTask() 然后 foo.execute(url1, url2, url3);foo.execute(url4, url5, url6);(如果你真的需要两个电话)
  • @mzeus.bolt 我已经创建了我的 asynctask 类的 2 个实例,但它仍然无法正常工作。
  • Toast.makeText(context,"There's no SD card",Toast....。您不能在 AsyncTask 的 doInBackground 中显示 Toast。您的应用程序将崩溃。此外,您继续使用您的代码,就好像卡片存在一样。不好。那你应该停下来。
  • apkStorage.mkdir();。检查返回值,因为它可能无法创建目录。在这种情况下,不要继续而是停止。

标签: android


【解决方案1】:

在给出您的代码时,您将以Intent 开头AsyncTask。这是错误的。

你需要检查AsyncTask的实现。

How to pass parameters and objects in AsyncTask

【讨论】:

  • 我应该如何将 MainActivity 的 url 提供给 DowloadTask?
【解决方案2】:

您的 AsyncTask 类用于下载一个文件。

您可以实例化您的类的两个实例来下载两个文件,但它们不会并行执行,而是一个接一个地执行。

如果您想并行使用它们,请使用 executeOnExecutor() 启动它们。

【讨论】:

  • 谢谢。问题已经解决了。现在它正在并行下载两个文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 2019-06-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
相关资源
最近更新 更多