我在尝试下载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();
}
}