Android Studio下载PDF文件并将其保存在SharedPreferences中

4

我在尝试下载PDF文件并将其保存在内部存储或共享偏好设置中以便读取时遇到了问题。是否有可能将其下载到内部存储中?我已经按照互联网上的几个教程进行了尝试,但是没有成功。请问有谁能指导我如何操作吗? 非常感谢。

package com.icul.downloadinternal;

import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    Button download, read;
    ImageView pdf;
    String url = "https://www.cdc.gov/eval/guide/cdcevalmanual.pdf";

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

        download = (Button) findViewById(R.id.button);
        read = (Button) findViewById(R.id.button2);
        pdf = (ImageView) findViewById(R.id.image);

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    downloadFileSync(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                String previouslyEncodedImage = shre.getString("pdf_data", "");

                if( !previouslyEncodedImage.equalsIgnoreCase("") ){
                    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0 , b.length);
                    pdf.setImageBitmap(bitmap);
                }
                else {
                    Toast.makeText(getApplicationContext(),"No File", Toast.LENGTH_LONG).show();
                }
            }
        });

    }
    public void downloadFileSync(String downloadUrl) throws Exception {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(downloadUrl).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Failed to download file: " + response);
        }

        String encodedImage = Base64.encodeToString(response.body().bytes(), Base64.DEFAULT);
        SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor edit = shre.edit();
        edit.putString("pdf_data", encodedImage);
        edit.commit();
    }
}

请更具体地说明,例如告诉我们您已经尝试了什么(在此处链接您的研究),以及在尝试下载PDF文件时遇到的问题是什么? - Kunal Chawla
存储在共享首选项中? - Rissmon Suresh
我想从URL下载一些PDF文件并将其保存在内部存储器中。我可以将其保存在SD卡或外部存储器中,但在我的项目中,PDF文件是私有的,因此必须保存在内部存储器中。 - rizal
2个回答

0

GRADLE

compile 'com.squareup.okhttp3:okhttp:3.8.0'

请编写:

public void downloadFileSync(String downloadUrl) throws Exception {

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(downloadUrl).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Failed to download file: " + response);
    }
    String encodedImage = Base64.encodeToString( response.body().bytes(), Base64.DEFAULT);

    SharedPreferences shre = 
    PreferenceManager.getDefaultSharedPreferences(this);
    Editor edit=shre.edit();
    edit.putString("pdf_data",encodedImage);
    edit.commit();
 }

阅读:

SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("pdf_data", "");

if( !previouslyEncodedImage.equalsIgnoreCase("") ){
    byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
    // .....
}

无法通过该方法下载 PDF。 - rizal

0
请将以下文件/方法添加到您的项目中:

  1. PdfDownloader.java
  2. PDFDownloaderAsyncTask.java

然后使用以下方法handleViewPdf来查看PDF:

private void handleViewPdf() {

    File folder = getAppDirectory(context);
    String fileName = "test.pdf";// getPdfFileName(pdfUrl);
    File pdfFile = new File(folder, fileName);

    if(pdfFile.exists() && pdfFile.length() > 0) {
        openPDFFile(context, Uri.fromFile(pdfFile));
    }
    else {
        if(pdfFile.length() == 0) {
            pdfFile.delete();
        }
        try {
            pdfFile.createNewFile();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
        ArrayList<String> fileNameAndURL = new ArrayList<>();
        fileNameAndURL.add(pdfFile.toString());
        fileNameAndURL.add(pdfUrl);
        fileNameAndURL.add(fileName);
        if(pdfDownloaderAsyncTask == null) {
            pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask(context, pdfFile);
        }
        if(hasInternetConnection(context)) {
            if(!pdfDownloaderAsyncTask.isDownloadingPdf()) {
                pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask(context, pdfFile);
                pdfDownloaderAsyncTask.execute(fileNameAndURL);
            }
        }
        else {
            //show error
        }
    }
}

PDFDownloaderAsyncTask.java

    import java.io.File;
    import java.util.ArrayList;

    import android.content.Context;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Handler;
    import android.text.TextUtils;
    import android.widget.Toast;


    public class PDFDownloaderAsyncTask extends AsyncTask<ArrayList<String>, Void, String> {

        private boolean isDownloadingPdf = false;

        private File    file;
        private Context context;

        public PDFDownloaderAsyncTask(Context context, File file) {

            this.file = file;
            this.context = context;
            this.isDownloadingPdf = false;
        }

        public boolean isDownloadingPdf() {

            return this.isDownloadingPdf;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
            //show loader etc
        }

        @Override
        protected String doInBackground(ArrayList<String>... params) {

            isDownloadingPdf = true;
            File file = new File(params[0].get(0));
            String fileStatus = PdfDownloader.downloadFile(params[0].get(1), file);
            return fileStatus;
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            Loader.hideLoader();
            if(!TextUtils.isEmpty(result) && result.equalsIgnoreCase(context.getString(R.string.txt_success))) {
                showPdf();
            }
            else {
                isDownloadingPdf = false;
                Toast.makeText(context, context.getString(R.string.error_could_not_download_pdf), Toast.LENGTH_LONG).show();
                file.delete();
            }
        }

        @Override
        protected void onCancelled() {

            isDownloadingPdf = false;
            super.onCancelled();
            //Loader.hideLoader();
        }

        @Override
        protected void onCancelled(String s) {

            isDownloadingPdf = false;
            super.onCancelled(s);
            //Loader.hideLoader();
        }

        private void showPdf() {

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {

                    isDownloadingPdf = false;
                    openPDFFile(context, Uri.fromFile(file));
                }
            }, 1000);
        }
    }

PdfDownloader.java

package com.pdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class PdfDownloader {
    private static final int MEGABYTE = 1024 * 1024;

    public static String downloadFile(String fileUrl, File directory) {

        String downloadStatus;
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            Log.d("PDF", "Total size: " + totalSize);
            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            downloadStatus = "success";
            fileOutputStream.close();
        }
        catch(FileNotFoundException e) {
            downloadStatus = "FileNotFoundException";
            e.printStackTrace();
        }
        catch(MalformedURLException e) {
            downloadStatus = "MalformedURLException";
            e.printStackTrace();
        }
        catch(IOException e) {
            downloadStatus = "IOException";
            e.printStackTrace();
        }
        Log.d("PDF", "Download Status: " + downloadStatus);
        return downloadStatus;
    }


    public static void openPDFFile(Context context, Uri path) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        try {
            context.startActivity(intent);
        }
        catch(ActivityNotFoundException e) {
            Toast.makeText(context, context.getString(R.string.txt_no_pdf_available), Toast.LENGTH_SHORT).show();
        }
        Loader.hideLoader();
    }

    public static File getAppDirectory(Context context) {

        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        File folder = new File(extStorageDirectory, context.getString(R.string.app_folder_name).trim());
        if(!folder.exists()) {
            boolean success = folder.mkdirs();
            Log.d("Directory", "mkdirs():" + success);
        }
        return folder;
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接