扩展AssyncTask的代码。出现错误
java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:596)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at com.monnfamily.libraryapp.Utility.DownloadManager.downloadBookData(DownloadManager.java:80)
at
package com.monnfamily.libraryapp.Utility;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadManager extends AsyncTask<String, Void, Boolean> {
private static final String TAG = "Download Manager";
public interface DownloadCompletedListner {
// you can define any parameter as per your requirement
public void downloadCompleted();
}
private BookProperties mBookDetails;
private DownloadCompletedListner mListner;
private static final DownloadManager mInstance = new DownloadManager();
public static DownloadManager getInstance() {
return mInstance;
}
private DownloadManager() {
}
@Override
protected Boolean doInBackground(String... strings) {
String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
tMainFolder += "/Book" + mBookDetails.getBookId();
downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_IMAGE + ".png", mBookDetails.getBookMainImage());
downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_AUDIO + ".mp3", mBookDetails.getBookSound());
for (PageDetailProperties pageDetails : mBookDetails.getPageDetail()) {
String tPageNumber = pageDetails.getPageNumber().toString();
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_IMAGE + tPageNumber + ".png", pageDetails.getPageImage());
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_AUDIO + tPageNumber + ".mp3", pageDetails.getPageAudio());
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_TEXT + tPageNumber + ".txt", pageDetails.getPageText());
}
return true;
}
protected void onPostExecute(Boolean result) {
//This is run on the UI thread so you can do as you wish here
if(result){
((LibraryView)BaseApplication.getInstance().getCurrentActivity()).hideActivityView();
mListner.downloadCompleted();
}
}
public void downloadBookData(BookProperties pBook){
mBookDetails = pBook;
String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
tMainFolder += "/Book" + pBook.getBookId();
File directory = new File(tMainFolder);
if (!directory.exists()) {
directory.mkdir();
((LibraryView)BaseApplication.getInstance().getCurrentActivity()).showActivityView();
new DownloadManager().execute(); /// error ocuures here
}
}
private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL){
try
{
URL url = new URL(pDownloadURL);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File directory = new File(pMainFolder, pFileName);
FileOutputStream outStream = new FileOutputStream(directory);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
//Add Network Error.
Log.e(TAG, "Download Error Exception " + e.getMessage());
e.printStackTrace();
}
}
public void setListner(DownloadCompletedListner pListner) {
this.mListner = pListner;
}
}
答案 0 :(得分:1)
您需要将DownloadManager与AsyncTask分开,创建另一个将扩展AsyncTask的类,例如MyDownloaderAsyncTask,该类将执行实际的后台工作,并且您的DownloadManager每次都会创建MyDownloaderAsyncTask的新实例并执行它。 您的课程应如下所示:
public class MyDownloaderAsyncTask extends AsyncTask<String, Void, Boolean> {
private DownloadManager.DownloadCompletedListner mListner;
private BookProperties mBookDetails;
public MyDownloaderAsyncTask(DownloadManager.DownloadCompletedListner listener, BookProperties bookdetails) {
mListner=listener;
mBookDetails=bookdetails;
}
@Override
protected Boolean doInBackground(String... strings) {
String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
tMainFolder += "/Book" + mBookDetails.getBookId();
downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_IMAGE + ".png", mBookDetails.getBookMainImage());
downloadBookDetails(tMainFolder, ContentfulConstants.BOOK_MAIN_AUDIO + ".mp3", mBookDetails.getBookSound());
for (PageDetailProperties pageDetails : mBookDetails.getPageDetail()) {
String tPageNumber = pageDetails.getPageNumber().toString();
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_IMAGE + tPageNumber + ".png", pageDetails.getPageImage());
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_AUDIO + tPageNumber + ".mp3", pageDetails.getPageAudio());
downloadBookDetails(tMainFolder, ContentfulConstants.PAGE_TEXT + tPageNumber + ".txt", pageDetails.getPageText());
}
return true;
}
protected void onPostExecute(Boolean result) {
//This is run on the UI thread so you can do as you wish here
if(result){
((LibraryView)BaseApplication.getInstance().getCurrentActivity()).hideActivityView();
mListner.downloadCompleted();
}
}
private void downloadBookDetails(String pMainFolder, String pFileName, String pDownloadURL){
try
{
URL url = new URL(pDownloadURL);
URLConnection ucon = url.openConnection();
ucon.setReadTimeout(5000);
ucon.setConnectTimeout(10000);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
File directory = new File(pMainFolder, pFileName);
FileOutputStream outStream = new FileOutputStream(directory);
byte[] buff = new byte[5 * 1024];
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff, 0, len);
}
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception e)
{
//Add Network Error.
Log.e(TAG, "Download Error Exception " + e.getMessage());
e.printStackTrace();
}
}
}
public class DownloadManager {
private static final String TAG = "Download Manager";
public interface DownloadCompletedListner {
// you can define any parameter as per your requirement
public void downloadCompleted();
}
private BookProperties mBookDetails;
private DownloadCompletedListner mListner;
private static final DownloadManager mInstance = new DownloadManager();
public static DownloadManager getInstance() {
return mInstance;
}
private DownloadManager() {
}
public void downloadBookData(BookProperties pBook){
mBookDetails = pBook;
String tMainFolder = String.valueOf(BaseApplication.getInstance().getAppContext().getDir("MonnFamily", Context.MODE_PRIVATE));
tMainFolder += "/Book" + pBook.getBookId();
File directory = new File(tMainFolder);
if (!directory.exists()) {
directory.mkdir();
((LibraryView)BaseApplication.getInstance().getCurrentActivity()).showActivityView();
new MyDownloaderAsyncTask(mListner, mBookDetails).execute(new String[]);
}
}
public void setListner(DownloadCompletedListner pListner) {
this.mListner = pListner;
}
}
答案 1 :(得分:0)
根据AsyncTask的线程规则部分:
该任务只能执行一次(如果出现以下情况,则会抛出异常: 尝试第二次执行。)
您只能执行一次AsyncTask
,因此无论何时要执行任务,都应始终创建一个新的:
new DownloadManager().execute(...);
代替:
DownloadManager dm = new DownloadManager();
dm.execute(...);
dm.execute(...); // throws IllegalStateException
您可能需要重构DownloadManager
类,或创建AsyncTask
的新子类。