我有一个问题。
我有两项活动。在第一个活动中,我使用asynctask从服务器下载文件,没关系。我有一个取消下载按钮。下载时,我点击按钮" 取消"要取消下载,我使用方法" myAsyntask.cancel(true)"为了这。它做得很好,但是当我改为第二个活动之后,我又回到第一个活动并点击按钮" 取消" - >我的App崩溃了。我调试并在更改活动时看到 myAsyntask 为空。
我该如何解决? 当我的应用更改为第二个活动并返回第一个活动时,我想取消asynctask
谢谢
这是myAsynctask
public class AsynDownload extends AsyncTask<GetParams, Integer, String> {
private Context context;
public AsynDownload(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
llDownloadItem.setVisibility(View.VISIBLE);
}
@Override
protected String doInBackground(GetParams... params) {
FunctionHelper.UpdateCacheDownBook(context, true);
checkDown = true;
String domain = params[0].domain;
String token = params[0].token;
String codeDevice = params[0].codeDevice;
String strPdf = "";
String strJsonPdf = "";
String strZip = "";
String strJsonZip = "";
Log.d("getdata", token + " - " + codeDevice);
try {
long total = 0;
long total_pdf = 0;
InputStream input_pdf = null;
OutputStream output_pdf = null;
HttpURLConnection connection_pdf = null;
InputStream input_zip = null;
OutputStream output_zip = null;
HttpURLConnection connection_zip = null;
JSONParser jsonParser = new JSONParser();
strPdf = domain + DOWNLOAD_BOOK + token + "/" + pdfFileId + "/" + codeDevice;
strJsonPdf = jsonParser.getJSONFromUrl(strPdf, METHOD_GET, null);
JSONObject object_Pdf = new JSONObject(strJsonPdf);
String path_pdf = object_Pdf.getString("DownloadsResult").toString();
URL url_pdf = new URL(path_pdf);
connection_pdf = (HttpURLConnection) url_pdf.openConnection();
connection_pdf.setRequestMethod("GET");
connection_pdf.connect();
if (connection_pdf.getResponseCode() != HttpURLConnection.HTTP_OK) {
FunctionHelper.UpdateCacheDownBook(context, false);
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
return "Server returned HTTP " + connection_pdf.getResponseCode()
+ " " + connection_pdf.getResponseMessage() + ". Vui lòng tải lại";
}
int fileLength_pdf = connection_pdf.getContentLength();
input_pdf = connection_pdf.getInputStream();
File root = new File(LIBOL_ROOT_PATH + proCode + "/");
if (!root.exists()) {
root.mkdirs();
} else {
FunctionHelper.DeleteRecursive(root);
root.mkdirs();
}
File pdf = new File(root, proCode + ".pdf");
if (!pdf.exists()) {
pdf.createNewFile();
}
long total_zip = 0;
strZip = domain + DOWNLOAD_BOOK + token + "/" + zipFileId + "/" + codeDevice;
strJsonZip = jsonParser.getJSONFromUrl(strZip, METHOD_GET, null);
JSONObject object_zip = new JSONObject(strJsonZip);
String path_zip = object_zip.getString("DownloadsResult").toString();
URL url_zip = new URL(path_zip);
connection_zip = (HttpURLConnection) url_zip.openConnection();
connection_zip.setRequestMethod("GET");
connection_zip.connect();
if (connection_zip.getResponseCode() != HttpURLConnection.HTTP_OK) {
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
FunctionHelper.UpdateCacheDownBook(context, false);
return "Server returned HTTPZip " + connection_zip.getResponseCode()
+ " " + connection_zip.getResponseMessage() + ". Vui lòng tải lại";
}
int fileLength_zip = connection_zip.getContentLength();
long lengOfFile = (long) fileLength_pdf + fileLength_zip;
output_pdf = new FileOutputStream(pdf, true);
byte data_pdf[] = new byte[4096];
int oldPercent = 0;
int count;
while ((count = input_pdf.read(data_pdf)) != -1) {
if (isCancelled()) {
input_pdf.close();
return null;
}
total += count;
output_pdf.write(data_pdf, 0, count);
int currentPercent = (int) (total * 100 / lengOfFile);
if (currentPercent > oldPercent) {
oldPercent = currentPercent;
Intent i = new Intent();
i.setAction(ACTION_FILTER);
i.putExtra("action", ACTION_SHOW_NOTIFICATION);
i.putExtra("BookId", bookId);
i.putExtra("BookName", bookName);
i.putExtra("LibraryId", libId);
i.putExtra("LibraryDomain", libDomain);
i.putExtra("LibraryName", libName);
if (isCancelled()) {
i.putExtra("action", ACTION_CANCEL_NOTIFICATION);
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
llDownloadItem.setVisibility(View.GONE);
} else {
i.putExtra("action", ACTION_SHOW_NOTIFICATION);
}
i.putExtra("percent", oldPercent);
if (oldPercent == 100) {
i.putExtra("show_percent", false);
} else {
i.putExtra("show_percent", true);
}
context.sendBroadcast(i);
}
}
Log.d("duythole3", "totalPDF =" + total_pdf);
output_pdf.flush();
output_pdf.close();
input_pdf.close();
input_zip = connection_zip.getInputStream();
File rootFile_zip = new File(LIBOL_ROOT_PATH);
File zipFile = new File(rootFile_zip, proCode + ".zip");
if (!rootFile_zip.exists()) {
rootFile_zip.mkdirs();
}
if (!zipFile.exists()) {
zipFile.createNewFile();
} else {
Boolean deletezip = zipFile.delete();
zipFile.createNewFile();
}
output_zip = new FileOutputStream(zipFile, true);
byte data_zip[] = new byte[1024 * 1024];
while ((count = input_zip.read(data_zip)) != -1) {
if (isCancelled()) {
input_zip.close();
return null;
}
total += count;
output_zip.write(data_zip, 0, count);
int currentPercent = (int) (total * 100 / lengOfFile);
if (currentPercent > oldPercent) {
oldPercent = currentPercent;
Intent i = new Intent();
i.setAction(ACTION_FILTER);
i.putExtra("action", ACTION_SHOW_NOTIFICATION);
i.putExtra("BookId", bookId);
i.putExtra("BookName", bookName);
i.putExtra("LibraryId", libId);
i.putExtra("LibraryDomain", libDomain);
i.putExtra("LibraryName", libName);
if (isCancelled()) {
i.putExtra("action", ACTION_CANCEL_NOTIFICATION);
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
llDownloadItem.setVisibility(View.GONE);
} else {
i.putExtra("action", ACTION_SHOW_NOTIFICATION);
}
i.putExtra("percent", oldPercent);
if (oldPercent == 100) {
i.putExtra("show_percent", false);
} else {
i.putExtra("show_percent", true);
}
context.sendBroadcast(i);
}
}
output_zip.flush();
output_zip.close();
input_zip.close();
Thread.sleep(500);
FunctionHelper.LibolUnzip(zipFile, zipFile.getParent(), proCode);
} catch (Exception e) {
return e.toString();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (DetailBookActivity.this.isDestroyed()) {
String countTimeEnd = String.valueOf(history.getRemainDate());
modelLibrary.OpenConnectionSQL(ctx);
modelLibrary.AddBookInfo(idBook, bookName, cover, proCode, author, publisher, libDomain, libId, libName, user, countTimeEnd);
modelLibrary.CloseConnection();
return;
}
if (result != null) {
FunctionHelper.UpdateCacheDownBook(context, false);
checkDown = false;
btnDownload.setText("Tải lại");
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
llDownloadItem.setVisibility(View.GONE);
File root = new File(LIBOL_ROOT_PATH + proCode);
FunctionHelper.DeleteRecursive(root);
Toast.makeText(context, "Có lỗi trong quá trình tải. Vui lòng tải lại", Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.setAction(ACTION_FILTER);
intent.putExtra("action", ACTION_LIBOL_DOWNLOAD_FAIL);
intent.putExtra("BookId", bookId);
context.sendBroadcast(intent);
} else {
FunctionHelper.UpdateCacheDownBook(context, false);
Log.d("tt", "tai thanh cong 1");
checkDown = false;
btnDownload.setVisibility(View.GONE);
btnXemsach.setVisibility(View.VISIBLE);
llDownloadItem.setVisibility(View.GONE);
Log.d("tt", "tai thanh cong 3");
String countTime = String.valueOf(history.getRemainDate());
modelLibrary.OpenConnectionSQL(ctx);
Boolean result_addbook = modelLibrary.AddBookInfo(idBook, bookName, cover, proCode, author, publisher, libDomain, libId, libName, user, countTime);
Log.d("addbook", result_addbook.toString());
modelLibrary.CloseConnection();
Toast.makeText(context, "Tải sách thành công", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(ACTION_FILTER);
intent.putExtra("action", ACTION_LIBOL_DOWNLOAD_COMPLETE);
intent.putExtra("BookId", bookId);
intent.putExtra("LibraryId", libId);
intent.putExtra("LibraryDomain", libDomain);
intent.putExtra("LibraryName", libName);
context.sendBroadcast(intent);
}
}
}
这是我称之为Asyntask的方法
private void DownLoadBook() {
if (FunctionHelper.isNetworkConnected(ctx)) {
GetParams getParams = new GetParams(libDomain, token, UniqueId);
asynDownload = new AsynDownload(ctx);
asynDownload.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, getParams);
} else {
Toast.makeText(ctx, "Không có kết nối internet", Toast.LENGTH_SHORT).show();
}
}
这是我用于取消Asynctask
的方法 private void CancelDownload() {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setTitle("Thông báo");
builder.setMessage("Bạn có muốn hủy tải cuốn sách này không?");
builder.setPositiveButton("Có", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
i.setAction(ACTION_FILTER);
i.putExtra("action", ACTION_CANCEL_NOTIFICATION);
i.putExtra("BookId", bookId);
ctx.sendBroadcast(i);
// llDownloadItem.setVisibility(View.GONE);
Boolean checkCache = FunctionHelper.GetCacheDownBook(ctx);
Log.d("checkCache", checkCache.toString());
if (checkCache) {
asynDownload.cancel(true);
FunctionHelper.UpdateCacheDownBook(ctx, false);
llDownloadItem.setVisibility(View.GONE);
}
File root = new File(LIBOL_ROOT_PATH + proCode);
FunctionHelper.DeleteRecursive(root);
modelLibrary.OpenConnectionSQL(ctx);
Boolean resultDelete = modelLibrary.DeleteBookSQlite(idBook);
Log.d("delete sqlite", resultDelete.toString());
modelLibrary.CloseConnection();
btnDownload.setVisibility(View.VISIBLE);
btnXemsach.setVisibility(View.GONE);
Toast.makeText(ctx, "Hủy tải sách thành công", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
这是第二个活动的按钮
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (TAG.equals("BOOK_IN_LIBRARY") || TAG.equals("LOGIN") || TAG.equals("SEARCH")) {
Intent iBookinLib = new Intent(ctx, BookInLibraryActivity.class);
iBookinLib.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
iBookinLib.putExtra("LibraryId", libId);
iBookinLib.putExtra("LibraryName", libName);
iBookinLib.putExtra("LibraryDomain", libDomain);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, iBookinLib, PendingIntent.FLAG_UPDATE_CURRENT);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
} else if (TAG.equals("BOOK_SHELF")) {
Intent iBookShelf = new Intent(ctx, BookShelfActivity.class);
iBookShelf.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, iBookShelf, PendingIntent.FLAG_UPDATE_CURRENT);
try {
pendingIntent.send();
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
}
}
}
});
答案 0 :(得分:0)
检查空指针是最简单的解决方案,
if (checkCache && asynDownload != null) {
asynDownload.cancel(true);
FunctionHelper.UpdateCacheDownBook(ctx, false);
llDownloadItem.setVisibility(View.GONE);
}
修改强>
将asyctask声明为静态对象,以便在从其他屏幕返回时将对象保留在内存中。