尝试下载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();
}
}
答案 0 :(得分:0)
摇篮
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);
// .....
}
答案 1 :(得分:0)
请将以下文件/方法添加到您的项目中
然后使用以下方法 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;
}
}