下载管理器问题

时间:2018-10-08 09:39:47

标签: java android

我有一个可以从链接下载文件的应用程序,但是它只能在棉花糖,牛轧糖上运行,我不知道,但是在Oreo和Pie中却无法下载。

这是执行下载的部分。 我在Android Oreo和Pie上测试了该应用程序,并显示了消息“发生错误”导致错误。我需要帮助,谢谢。

 @Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        Toast.makeText(MainActivity.this, "="+f_url, Toast.LENGTH_LONG).show();
        URLConnection connection = url.openConnection();
        connection.connect();
        // getting file length

        int lengthOfFile = connection.getContentLength();
        Toast.makeText(MainActivity.this,"length="+lengthOfFile , Toast.LENGTH_LONG).show();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        String timestamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

        //Extract file name from URL
        fileName = f_url[0].substring(f_url[0].lastIndexOf('/') + 1, f_url[0].length());

        //Append timestamp to file name
        fileName = timestamp + "_" + fileName;

        //External directory path to save file
        folder = Environment.getExternalStorageDirectory() + File.separator + "androiddeft/";

        //Create androiddeft folder if it does not exist
        File directory = new File(folder);

        if (!directory.exists()) {
            directory.mkdirs();
        }

        // Output stream to write file
        OutputStream output = new FileOutputStream(folder + fileName);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress("" + (int) ((total * 100) / lengthOfFile));
            Log.d(TAG, "Progress: " + (int) ((total * 100) / lengthOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();
        return "Downloaded at: " + folder + fileName;

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return "Something went wrong";
}

0 个答案:

没有答案