android cant open pdf from cache dir

2019-07-20 02:58发布

Trying to download and open a pdf file from internet using HTTPClient on android. I have 2 classes. First one is the parser class that has the next method:

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();
    }
}

The next class is an Activity. It makes a new Intent and opens pdf file using installed software (user decides what soft to use). This Activity saves the pdf file using the upper method from Parser.class and AsyncTask. It looks so:

   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();
        }
    }

}

While the Log.e("FILE EXISTS?",""+file.exists()) sais, that the file exists, it doesnot want to be opened with any of 8 pdf readers I tryed to use. Please help.Thanks in advance

1条回答
Evening l夕情丶
2楼-- · 2019-07-20 03:45

Those "8 pdf readers" have no access to your cache directory. Either store it on external storage (e.g., getExternalCacheDir()), or create a ContentProvider to serve the PDF out of your internal cache dir. This sample project demonstrates serving a file from internal storage.

查看更多
登录 后发表回答