Android 意图不打开pdf文件

Android 意图不打开pdf文件,android,firebase,pdf,firebase-storage,Android,Firebase,Pdf,Firebase Storage,我找到了这个答案,我尝试了这个代码,它弹出对话框选择pdfviewer,当我点击AdobeReader时,它只是启动AdobeReader,但不启动pdf文件 代码片段 pdflistView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, Vie

我找到了这个答案,我尝试了这个代码,它弹出对话框选择pdfviewer,当我点击AdobeReader时,它只是启动AdobeReader,但不启动pdf文件

代码片段

pdflistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

               UploadPDF uploadPDF = list.get(position);
               String url = uploadPDF.getUrl();
               Log.i("url",url);
                Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
                intent.setType("application/pdf");
                PackageManager pm = getPackageManager();
                List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
                if (activities.size() > 0) {
                    startActivity(intent);
                } else {
                    // Do something else here. Maybe pop up a Dialog or Toast
                    Toast.makeText(ShowPdfActivity.this, "Can't open pdf", Toast.LENGTH_SHORT).show();
                }
正如您在logcat中看到的,我正在获取url,但无法启动默认/已安装的pdf查看器


谢谢

为了满足您的需要,您需要下载PDF并将其存储到设备存储器中,这样您就可以使用它们的路径来使用它

以下是如何下载PDF文件并在下载完成后打开该文件的完整示例:

String PDF_URL = "https://perso.univ-rennes1.fr/pierre.nerzic/Android/poly.pdf";



@SuppressLint("StaticFieldLeak")
private class DownloadFile extends AsyncTask<String, Integer, String> {

    String savedFilePath = null;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //To ignore the file URI exposure.
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        progressDialog = new ProgressDialog(PickLocationActivity.this);
        progressDialog.setTitle("Downloading PDF");
        progressDialog.setMessage("Please wait (0%)");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... urlParams) {
        int count;
        String fileName = urlParams[1] + ".pdf";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        + "/PDF_FOLDER/");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }
        if (success) {
            File file = new File(storageDir, fileName);
            savedFilePath = file.getAbsolutePath();
            if (!file.exists()) {
                try {
                    URL url = new URL(urlParams[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    int lenghtOfFile = conexion.getContentLength();
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream(file);
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return savedFilePath;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setMessage("Please wait (" + values[0] + "%)");
    }

    @Override
    protected void onPostExecute(String pdfPath) {
        super.onPostExecute(pdfPath);
        if (pdfPath != null && !pdfPath.isEmpty()) {
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                progressDialog.dismiss();
                Uri path = Uri.fromFile(pdfFile);
                Intent Go = new Intent(Intent.ACTION_VIEW);
                Go.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Go.setDataAndType(path, "application/pdf");
                Go.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(Go);
            }
        }
    }
}
String PDF\u URL=”https://perso.univ-rennes1.fr/pierre.nerzic/Android/poly.pdf";
@SuppressLint(“StaticFieldLeak”)
私有类下载文件扩展异步任务{
字符串savedFilePath=null;
进行对话进行对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//忽略文件URI暴露。
StrictMode.VmPolicy.Builder=新的StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
progressDialog=新建progressDialog(PickLocationActivity.this);
progressDialog.setTitle(“下载PDF”);
progressDialog.setMessage(“请稍候(0%)”;
progressDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…urlparms){
整数计数;
字符串文件名=urlparms[1]+“.pdf”;
File storageDir=新文件(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY\u下载)
+“/PDF\u FOLDER/”;
布尔成功=真;
如果(!storageDir.exists()){
success=storageDir.mkdirs();
}
如果(成功){
文件=新文件(storageDir,文件名);
savedFilePath=file.getAbsolutePath();
如果(!file.exists()){
试一试{
URL=新的URL(URL参数[0]);
URLConnection conexion=url.openConnection();
conexion.connect();
int lenghtOfFile=conexion.getContentLength();
InputStream输入=新的BufferedInputStream(url.openStream());
OutputStream output=新文件OutputStream(文件);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
出版进度(整数)(总计*100/长办公室);
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
}捕获(例外e){
e、 printStackTrace();
}
}
}
返回savedFilePath;
}
@凌驾
受保护的void onProgressUpdate(整型…值){
super.onProgressUpdate(值);
setMessage(“请稍候(“+值[0]+”%)”);
}
@凌驾
受保护的void onPostExecute(字符串pdfPath){
super.onPostExecute(pdfPath);
if(pdfPath!=null&&!pdfPath.isEmpty()){
文件pdfFile=新文件(pdfPath);
if(pdfFile.exists()){
progressDialog.disclose();
Uri路径=Uri.fromFile(pdfFile);
意向Go=新意向(意向.行动\视图);
Go.addFlags(Intent.FLAG\u GRANT\u READ\u URI\u PERMISSION);
Go.setDataAndType(路径,“application/pdf”);
Go.setFlags(意图、标志、活动、清除、顶部);
星触觉(Go);
}
}
}
}
可以这样称呼它:
newdownloadfile().execute(PDF_URL,“PDF_NAME”)
不要忘记在您的AndroidManifest.xml上添加
互联网
读取外部存储
写入外部存储
权限



否则,您可以使用此库并从URL转到远程PDF,它也在做同样的事情(先将PDF文件下载到设备存储中)

为了满足您的需要,您需要下载PDF并将其存储到设备存储中,以便您可以使用它们的路径来使用它

以下是如何下载PDF文件并在下载完成后打开该文件的完整示例:

String PDF_URL = "https://perso.univ-rennes1.fr/pierre.nerzic/Android/poly.pdf";



@SuppressLint("StaticFieldLeak")
private class DownloadFile extends AsyncTask<String, Integer, String> {

    String savedFilePath = null;
    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //To ignore the file URI exposure.
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        progressDialog = new ProgressDialog(PickLocationActivity.this);
        progressDialog.setTitle("Downloading PDF");
        progressDialog.setMessage("Please wait (0%)");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... urlParams) {
        int count;
        String fileName = urlParams[1] + ".pdf";
        File storageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                        + "/PDF_FOLDER/");
        boolean success = true;
        if (!storageDir.exists()) {
            success = storageDir.mkdirs();
        }
        if (success) {
            File file = new File(storageDir, fileName);
            savedFilePath = file.getAbsolutePath();
            if (!file.exists()) {
                try {
                    URL url = new URL(urlParams[0]);
                    URLConnection conexion = url.openConnection();
                    conexion.connect();
                    int lenghtOfFile = conexion.getContentLength();
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream(file);
                    byte data[] = new byte[1024];
                    long total = 0;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress((int) (total * 100 / lenghtOfFile));
                        output.write(data, 0, count);
                    }
                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return savedFilePath;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressDialog.setMessage("Please wait (" + values[0] + "%)");
    }

    @Override
    protected void onPostExecute(String pdfPath) {
        super.onPostExecute(pdfPath);
        if (pdfPath != null && !pdfPath.isEmpty()) {
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                progressDialog.dismiss();
                Uri path = Uri.fromFile(pdfFile);
                Intent Go = new Intent(Intent.ACTION_VIEW);
                Go.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Go.setDataAndType(path, "application/pdf");
                Go.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(Go);
            }
        }
    }
}
String PDF\u URL=”https://perso.univ-rennes1.fr/pierre.nerzic/Android/poly.pdf";
@SuppressLint(“StaticFieldLeak”)
私有类下载文件扩展异步任务{
字符串savedFilePath=null;
进行对话进行对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//忽略文件URI暴露。
StrictMode.VmPolicy.Builder=新的StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
progressDialog=新建progressDialog(PickLocationActivity.this);
progressDialog.setTitle(“下载PDF”);
progressDialog.setMessage(“请稍候(0%)”;
progressDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…urlparms){
整数计数;
字符串文件名=urlparms[1]+“.pdf”;
File storageDir=新文件(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY\u下载)
+“/PDF\u FOLDER/”;
布尔成功=真;
如果(!storageDir.exists()){
success=storageDir.mkdirs();
}
如果(成功){
文件=新文件(storageDir,文件名);
savedFilePath=file.getAbsolutePath();
如果(!file.exists()){
试一试{
URL=新的URL(URL参数[0]);
URLConnection conexion=url.openConnection();
conexion.connect();
int lenghtOfFile=co
String url = "given";
 DownloadManager downloadmanager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                    request.setTitle(name);
                    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
                            DownloadManager.Request.NETWORK_MOBILE);
                   request.setAllowedOverRoaming(false);
                    request.setDescription("Downloading");
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,name);
                    request.setMimeType(".pdf");

                    id = downloadmanager.enqueue(request);