我在我的應用程序中有一個按鈕,單擊它時將打開一個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,但不是其他兩種方法!也許這就是爲什麼文件不存在的地方,它應該是 –