我正在尝试从 Internet 下载 pdf,将文件存储在内部存储中,然后有意启动 pdf。启动意图时,我不断收到“文档为空(大小为 0KB)”。
class Pdf extends AsyncTask<Void, Void, String>{
private Context ctx;
public Pdf(Context ctx){
this.ctx = ctx;
}
@Override
protected String doInBackground(Void... params) {
try {
FileOutputStream f = ctx.openFileOutput("city.pdf", ctx.MODE_WORLD_READABLE);
URL u = new URL("http://www.example.com/city.pdf");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(ctx.getFilesDir(), "city.pdf");
PackageManager packageManager = ctx.getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
ctx.startActivity(intent);
return null;
}
}
这一直让我发疯,有什么想法吗?