繁体   English   中英

在Android中打开pdf时出现问题:无效的文件路径

[英]Problems opening pdf in Android: Invalid file path

我需要从我的Android应用程序打开pdf文件。 我将pdf保存在应用程序包文件夹(/data/data/com.app.example/files)中。 我已经在Android模拟器中安装了Adobe Reader应用程序。 问题是,当我尝试使用Adobe Reader打开pdf文件时,模拟器向我显示了下一条消息:无效的文件路径。

我不知道为什么会这样,但我坚持这一点。 该文件已正确保存,因为我可以在计算机上打开它。

这是代码:

HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            request(response, file_name);

            File file = new File("data/data/com.app.example/files/"+file_name);

            PackageManager packageManager = getPackageManager();
            Intent testIntent = new Intent(Intent.ACTION_VIEW);
            testIntent.setType("application/pdf");
            List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
            if(file.exists())
            {
                  if (list.size() > 0 && file.isFile()) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        Uri uri = Uri.fromFile(file);
                        intent.setDataAndType(uri, "application/pdf");
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);     

                        startActivity(intent);
                  }else
                  {
                        System.out.println("NO APPs TO OPEN PDFs.");
                  }
            }
            else
            {
                  System.out.println("FILE DOES NOT EXIST.");
            }           
        }catch(Exception ex){
            System.out.println("Failed!");
            ex.printStackTrace();
        }


public String request(HttpResponse response, String file){
        String result = "";
        try{
            InputStream in = response.getEntity().getContent();
            FileOutputStream f = openFileOutput(file, MODE_WORLD_WRITEABLE);
            byte[] buffer = new byte[in.toString().length()];
            int len1 = 0;
            int counter = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
                counter++;
            }
            f.close();
        }
        catch(Exception ex){
            result = "Error";
        }
        return result;
    }

提前致谢。

问候,哈维。

这是因为PDF文件位于您自己的程序包中,而Adobe Reader试图从您的程序包中访问PDF文件,这是Android应用程序开发所不允许的。

您可以尝试将文件保存在SDCARD上,然后将其打开

不要使用直接路径访问应用程序私有的文件。 改为使用

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);

请参阅: http : //developer.android.com/guide/topics/data/data-storage.html#filesInternal

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM