我的应用程序中有一个按钮,单击此按钮将打开PDF(将显示“打开方式”提示)。 PDF文件位于应用程序的资产文件夹中。我编写了代码,以便AsyncTask执行从assets文件夹复制到外部存储的操作,然后打开它。然而,在运行时,AsyncTask类的所有方法都没有执行,就像我从Logcat中看到的那样。我已经看到了其他类似的问题,并尝试了不同的答案:
我得到的错误是onPostExecute(文件文件)方法中的NullPointerException,即找不到文件。这三种方法中没有记录的语句都在logcat中。
我在下面调用这个执行方法:
public void execute(){
Context context = contextWeakReference.get();
if (context != null) {
new CopyFileAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[])null);
}
}
private class CopyFileAsyncTask extends AsyncTask<Void, Void, File> {
final String appDirectoryName = BuildConfig.APPLICATION_ID;
final File fileRoot = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), appDirectoryName);
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("AsyncTask", "onPreExecute");
}
@Override
protected File doInBackground(Void... params) {
Context context = contextWeakReference.get();
AssetManager assetManager = context.getAssets();
File file = new File(fileRoot, fileName);
InputStream in = null;
OutputStream out = null;
try {
file.mkdirs();
if (file.exists()) {
file.delete();
}
file.createNewFile();
in = assetManager.open(fileName);
Log.d(TAG, "In");
out = new FileOutputStream(file);
Log.d(TAG, "Out");
Log.d(TAG, "Copy file");
copyFile(in, out);
Log.d(TAG, "Close");
in.close();
out.flush();
out.close();
return file;
} catch (Exception e)
{
Log.e(TAG, e.getMessage());
}
return null;
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
@Override
protected void onPostExecute(File file) {
super.onPostExecute(file);
Context context = contextWeakReference.get();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(file),
"application/pdf");
context.startActivity(intent);
}
}
答案 0 :(得分:1)
您始终在 doInBackground
中返回null所以
protected void onPostExecute(File file) {
super.onPostExecute(file);
Context context = contextWeakReference.get();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.fromFile(file),
"application/pdf");
context.startActivity(intent);
}
文件始终空
尝试编辑此
@Override
protected File doInBackground(Void... params) {
Context context = contextWeakReference.get();
AssetManager assetManager = context.getAssets();
File file = new File(fileRoot, fileName);
InputStream in = null;
OutputStream out = null;
try {
file.mkdirs();
if (file.exists()) {
file.delete();
}
file.createNewFile();
in = assetManager.open(fileName);
Log.d(TAG, "In");
out = new FileOutputStream(file);
Log.d(TAG, "Out");
Log.d(TAG, "Copy file");
copyFile(in, out);
Log.d(TAG, "Close");
in.close();
out.flush();
out.close();
} catch (Exception e)
{
Log.e(TAG, e.getMessage());
}
return file;
}
答案 1 :(得分:0)
问题解决了!!显然,Marshmallow在幕后工作中做了一些秘密,比如不要求权限(使用android studio安装时)。我发现android mkdirs not working的答案对我有用。你必须去设置&gt;应用&gt;你的应用&gt;启用存储权限。我花了三天时间来解决这个问题!