2017-04-20 2 views
1

J'ai un problème. J'ai deux activité. Dans le première activité, j'utilise asynctask pour télécharger le fichier à partir du serveur, c'est ok. J'ai un bouton pour annuler le téléchargement. Pendant le téléchargement, je clique sur le bouton "Annuler" pour annuler le téléchargement, j'utilise la méthode "myAsyntask.cancel (true)" pour cela. Ca va bien, mais quand je change seconde activité et après cela, je reviens à la première activité et cliquez sur le bouton "Annuler " -> mon accident de l'App. Je débogue et vois myAsyntask est null lorsque l'activité de changement.Asynctask égal à zéro lors de la modification de la deuxième activité et de la première activité de retour

Comment puis-je résoudre ce problème? Je veux annuler AsyncTask quand mon changement d'application à la seconde activité et revenir première activité

Merci

C'est 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); 
     } 
    } 


} 

Ceci est la méthode que j'appelle 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(); 
    } 
} 

Et c'est la méthode que j'utilise pour annuler 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(); 

} 

C'est le bouton pour venir à la seconde activité

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

Vous pouvez vérifier si la tâche async est nul avant d'annuler la tâche – Sony

+0

paramètre de contrôle vous passez ce sera nul ou non –

+0

montrer un code d'activité aussi afin que nous puissions obtenir votre cas –

Répondre

0

Recherche d'un pointeur NULL est la solution la plus simple,

if (checkCache && asynDownload != null) { 

       asynDownload.cancel(true); 

       FunctionHelper.UpdateCacheDownBook(ctx, false); 
       llDownloadItem.setVisibility(View.GONE); 

      } 

EDIT:

Declare asyctask comme objet statique conserver l'objet en mémoire en revenant d'autres écrans.

+0

mais que s'il veut annuler l'asynctask, null vérifier ne aidera pas dans ce cas –

+0

Merci, mais je veux dire, je veux annuler le téléchargement alors que le changement à la deuxième activité et le retour en premier activité. Votre code ne peut pas annuler mon Asyntask, j'avais l'habitude de le faire. –

+0

Pouvez-vous essayer de déclarer l'asynctask comme un objet statique –