我在我的应用程序中有一个按钮,单击它时将打开一个PDF(将显示“Open with”提示符)。 PDF文件位于应用程序的资产文件夹中。我已经编写了代码,以便AsyncTask执行从资产文件夹复制到外部存储并将其打开的操作。但是在运行时,AsyncTask类的方法都没有执行,正如我从Logcat中看到的那样。我见过其他类似的问题,并试图自己不同的答案:AsyncTask没有任何方法调用
- .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)代替.execute()
- .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(太虚[])NULL);
- 加入onPreExecute()
我得到的错误是空指针异常的onPostExecute(档案文件)的方法,即文件未找到。这三种方法中的记录语句都不在logcat中。
我把下面这个execute方法:
公共无效的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);
}
}
非常感谢!应用程序运行并出现“打开方式”对话框。出现Adobe Reader的闪存屏幕,但是我收到一条吐司消息:“无法访问该文件,请检查位置或网络,然后重试”。你能帮我解决这个问题吗? –
另一点:我用其他应用程序,他们也无法打开它。看起来好像该文件不在该目录中。 –
另外!我再次检查日志:遇到onPreExecute,但不是其他两种方法!也许这就是为什么文件不存在的地方,它应该是 –