【问题标题】:Downloading a single file with AsyncTask使用 AsyncTask 下载单个文件
【发布时间】:2018-10-28 06:13:35
【问题描述】:

我是 Android 开发的初学者。我正在尝试学习多线程并使用互联网,所以我通过使用AsyncTask 通过后台线程的链接从链接下载 PDF 文件来做到这一点。我不知道最好的方法是什么。

我是在onCreateAsyncTask 类的doInBackground 方法中创建URI 和其他必要的连接对象吗?

要仅下载单个 PDF 文件,我需要调用哪些类型的对象?

我已经检查了文档,但我无法真正理解它。我会很感激外行的解释和可能的伪代码。

这是我目前的代码:

public class MainActivity extends AppCompatActivity {
    Button downloadPDF;
    DownloadingClass downPDF;
    private static final String TAG = "omar.asynctaskdemo;";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String urlExample = "https://doc.lagout.org/programmation/Actionscript%20-%20Flash%20-%20Flex%20-%20Air/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29/Flash%20Development%20for%20Android%20Cookbook%20-%20Labrecque%20-%20Packt%20%282011%29.pdf");

        downloadPDF = findViewById(R.id.download_pdf);
        downPDF = new DownloadingClass();

        downloadPDF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downPDF.execute();
            }
        });
    }

    private class DownloadingClass extends AsyncTask<String, Integer, Void>{
        @Override
        protected Void doInBackground(String... strings) {
            return null;
        }
    }
}

【问题讨论】:

  • AsyncTask Android example的可能重复
  • @AliKhaki 这是一个通用的 Asynctask 问题。我问的是最佳实践。连接代码在哪里?

标签: android multithreading android-asynctask


【解决方案1】:

AsyncTask 只是在后台线程中运行您的代码。下载 pdf 文件就像下载其他文件一样。

您将需要使用HttpUrlConnection,创建FileOutputStream 并编写inputstream。参考this

在 AsyncTask 类的doInBackground 中执行上述代码,最好在构造函数中传递 url 并在 doInBackground 方法中执行所有操作。因为你不想阻塞 UI 线程。

【讨论】:

  • 哪个构造函数?
  • new DownloadingClass("在这里传递你的网址")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-22
相关资源
最近更新 更多