【问题标题】:pdf not getting downloaded in pre-lollipop devices using download manager使用下载管理器无法在棒棒糖之前的设备中下载 pdf
【发布时间】:2016-10-12 11:06:42
【问题描述】:

我正在尝试使用 DownloadManager 下载 pdf。

我在链接中传递参数,并从生成并下载到设备的服务器 pdf 文件中传递参数。所以我的下载链接会是这样的

http://example.com/gen.php?data={......}

我的代码:

final Request request = new Request(Uri.parse(fromUrl));
request.setMimeType("application/pdf");
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(path, "ELALA_MANIFEST_" + System.currentTimeMillis() + ".pdf");

final DownloadManager dm = (DownloadManager) context
        .getSystemService(Context.DOWNLOAD_SERVICE);
try {
    try {
        dm.enqueue(request);
    } catch (SecurityException e) {
        request.setNotificationVisibility(Request.VISIBILITY_VISIBLE);
        Log.e("Error", e.toString());
        dm.enqueue(request);
    }

}
// if the download manager app has been disabled on the device
catch (IllegalArgumentException e) {
    openAppSettings(context,
            AdvancedWebView.PACKAGE_NAME_DOWNLOAD_MANAGER);
}

在 api 级别 21(棒棒糖)及更高级别的设备上运行良好。但在较低版本的 pdf 中没有被下载。并弹出通知,

<untitled> download unsuccessful

我知道这与setMimeType 有关,但不知道是什么。

任何帮助将不胜感激。

【问题讨论】:

  • 其他文件类型在你的 pre-lollipop 上工作正常吗?
  • @KamranAhmed 是的...
  • 你能用adb root &amp;&amp; adb pull /data/data/com.android.providers.downloads/databases/downloads.db .获取DownloadManager数据库吗?
  • 我不知道如何发胖。你能解释一下吗?
  • 尝试在您的棒棒糖之前的设备上下载 PDF 文件,一旦失败,将其连接到 PC 并在终端中运行 adb root &amp;&amp; adb pull /data/data/com.android.providers.downloads/databases/downloa‌​ds.db .

标签: android pdf android-download-manager


【解决方案1】:

当您收到&lt;untitled&gt; download unsuccessful 时,通常表示您的网址不正确、为空或为空。所以首先请确保 url 是好的。

看看我在 4.4 (pre-lolipop) 中运行的 DownloadManager 的小例子。

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private DownloadManager dm;
    private String url;

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

        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        url = "https://collegereadiness.collegeboard.org/pdf/psat-nmsqt-practice-test-1.pdf";

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(url)) {
                    throw new IllegalArgumentException("url cannot be empty or null");
                }

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

                if (isExternalStorageWritable()) {
                    String uriString = v.getContext().getExternalFilesDir(null) + "";
                    File file = new File(uriString, Uri.parse(url).getLastPathSegment());
                    Uri destinationUri = Uri.fromFile(file);
                    request.setDestinationUri(destinationUri);
                    dm.enqueue(request);
                }
            }
        });

        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                Log.d(TAG, "onReceive() returned: " + action);
                // TODO: 2016-10-12  
            } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
                Log.d(TAG, "onReceive() returned: " + action);
                // TODO: 2016-10-12  
            }
        }
    };

    private static final String TAG = "MainActivity";

    //...

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}

它使用权限:

 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

处理所有情况很重要。也可以尝试使用应用程序目录而不是乱七八糟,即在你的 SD 卡上。此示例将下载的文件保存在 /sdcard/Android/data/{your app package name}/files/。以前我检查我是否已安装 sdcard 以及是否可以在目录上写入。

示例:


好的,如果标题有“Content-Disposition”字段,这是我的解析文件名的示例。你说它在你的服务器上,所以你可以做到:)

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private DownloadManager dm;
    private String url;

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

        dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        url = "http://dl1.shatelland.com/files/07610a8d-a73f-45bb-8868-6fd33299bda7/6e33639f-0ce0-43ef-86e4-43492db1be86";

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downloadFileInTask(v.getContext(), url);
                    }
                }).start();
            }
        });

        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private void downloadFileInTask(Context v, String url) {
        if (TextUtils.isEmpty(this.url)) {
            throw new IllegalArgumentException("url cannot be empty or null");
        }

        /*when redirecting from hashed url and found headerField "Content-Disposition"*/
        String resolvedFile = resolveFile(url, "unknown_file");

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        if (isExternalStorageWritable()) {
            File file = new File(v.getExternalFilesDir(null), resolvedFile);
            Uri destinationUri = Uri.fromFile(file);
            request.setDestinationUri(destinationUri);
            dm.enqueue(request);
        }
    }

    private String resolveFile(String url, String defaultFileName) {
        String filename = defaultFileName;

        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) new URL(url).openConnection();
            con.setInstanceFollowRedirects(true);
            con.connect();

            String contentDisposition = con.getHeaderField("Content-Disposition");
            if (!TextUtils.isEmpty(contentDisposition)) {
                String[] splittedCD = contentDisposition.split(";");
                for (int i = 0; i < splittedCD.length; i++) {
                    if (splittedCD[i].trim().startsWith("filename=")) {
                        filename = splittedCD[i].replaceFirst("filename=", "").trim();
                        break;
                    }
                }
            }

            con.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return filename;
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                Log.d(TAG, "onReceive() returned: " + action);
                // TODO: 2016-10-12  
            } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
                Log.d(TAG, "onReceive() returned: " + action);
                // TODO: 2016-10-12  
            }
        }
    };

    private static final String TAG = "MainActivity";

    //...

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state);
    }

    public boolean isExternalStorageReadable() {
        String state = Environment.getExternalStorageState();
        return Environment.MEDIA_MOUNTED.equals(state) ||
                Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
    }
}

【讨论】:

  • 感谢您的回复。但我是我的情况 pdf 没有保存在服务器上的某个地方。它是从我传递的参数生成的。所以我的下载链接会是这样的http://example.com/gen.php?data={......}
  • 好的,谢谢,我会尝试编辑我的答案。请在创建问题时更具体。 :)
  • 等等..我会带着样品回来的。
猜你喜欢
  • 1970-01-01
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2016-02-11
  • 2018-09-01
  • 2016-08-14
  • 1970-01-01
相关资源
最近更新 更多