android无法从缓存目录打开pdf

标签 android file caching httpclient

尝试在 android 上使用 HTTPClient 从 Internet 下载并打开 pdf 文件。我有2节课。第一个是具有下一个方法的解析器类:

public static void saveFile(String link, FileOutputStream fos) {
    DefaultHttpClient client = new DefaultHttpClient();
    try{
        client.setCookieStore(cookieStore);
        HttpGet method = new HttpGet(link);
        HttpResponse response = client.execute(method);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.writeTo(fos);
            fos.close();
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        client.getConnectionManager().shutdown();
    }
}

下一个类是一个 Activity 。它创建一个新的 Intent 并使用安装的软件打开 pdf 文件(用户决定使用什么软件)。此 Activity 使用 Parser.class 和 AsyncTask 中的上层方法保存 pdf 文件。看起来是这样的:

   private class AsyncExecutionOfPdf extends AsyncTask<Void,Void,Void>{
    @Override
    protected Void doInBackground(Void... arg0) {
        File file;
        file = new File(getCacheDir()+"/tempFile.pdf");
        file.setWritable(true);
        file.setReadable(true);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Parser.saveFile("http://existingInternetFile.pdf", fos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(Void resu) {
        pd.dismiss();
        Intent intent = new Intent(Intent.ACTION_VIEW);
        File file = new File(getCacheDir()+"/tempFile.pdf");
        Log.e("FILE EXISTS?",""+file.exists());
        intent.setDataAndType(Uri.fromFile(file), "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            startActivity(intent);
        } 
        catch (ActivityNotFoundException e) {
            Toast.makeText(FilesActivity.this, 
                "No Application Available to View PDF", 
                Toast.LENGTH_SHORT).show();
        }
    }

}

虽然 Log.e("FILE EXISTS?",""+file.exists()) 表示文件存在,但它不想用我尝试使用的 8 个 pdf 阅读器中的任何一个打开。请帮助。提前致谢

最佳答案

那些“8 个 pdf 阅读器”无法访问您的缓存目录。将其存储在外部存储设备上(例如,getExternalCacheDir()),或创建一个 ContentProvider 以从您的内部缓存目录提供 PDF。 This sample project演示了从内部存储提供文件。

关于android无法从缓存目录打开pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16748218/

相关文章:

Android - 保持/存储加载的 JSON 的良好做法

java - Android 操作栏使用 customlitview 进行搜索

javascript - java中ajax post调用的等效方法

java - 在java中查找特定命名方案的所有文件

java - 如何将泛型类型存储在缓存中以避免在检索时进行未经检查的强制转换?

android - java.util.zip.ZipException Android Studio

java - 这段代码 fragment 是什么意思

delphi - 如何检测流结束?

java - Spring + Hibernate 与 Hazelcast 作为二级缓存

php - 如何正确服务 CSS