Android让AsyncTask等待活动在for循环中恢复

时间:2017-08-24 11:17:20

标签: android loops android-asynctask

我在onActivityResult()方法中有一个for循环,用于创建Runnable对象并分配到AsyncTask。每个Runnable对象负责操作pdf文件,使用密码对其进行密封,然后使用startActivityForResult()启动Intent方法发送电子邮件。

除了我的问题是for循环将立即启动所有AsyncTask,即使活动暂停且用户在电子邮件客户端应用程序上,一切都可以作为魅力。我想确保下一个AsyncTask不会执行,直到用户在电子邮件客户端应用程序上按下发送电子邮件按钮后返回应用程序。

更新

 if (requestCode == 2) {
        // Create Insurer annexe, seal document with insurer password and trigger sending email
        int lastInsurerPosition = -1;
        for (int i = 0; i < Constat.getInstance().getAccidentList().size(); i++) {
            if (Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition() != -1 &&
                    !insurersEmails[Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition()].equals("null") &&
                    Constat.getInstance().getAccidentList().get(i).getSendOption() != 1 &&
                    Constat.getInstance().getAccidentList().get(i).getSendOption() != 2) {
                lastInsurerPosition = i;
            }
        }
        if (lastInsurerPosition != -1) {
            final int lastInsurerPositionCopy = lastInsurerPosition;

            for (int i = 0; i < Constat.getInstance().getAccidentList().size(); i++) {
                String insurerEmail = "null";
                if (Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition() != -1) {
                    insurerEmail = insurersEmails[Constat.getInstance().getAccidentList().get(i).getCar().getInsurerPosition()];
                }
                if (Constat.getInstance().getAccidentList().get(i).getSendOption() != 1 &&
                        Constat.getInstance().getAccidentList().get(i).getSendOption() != 2 &&
                        !insurerEmail.equals("null")) {
                    final int finalI = i;
                    Runnable progressRunnable = new Runnable() {
                        @Override
                        public void run() {
                            try {
                                String[] toArray = new String[1];
                                toArray[0] = insurersEmails[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()];
                                String subject = getResources().getString(R.string.pdf_joint_report);

                                InputStream is;
                                String str;
                                byte[] buffer = null;
                                int size;

                                if (Locale.getDefault().getLanguage().equals("en")) {
                                    is = getAssets().open("insurerEmailTemplateENG.html");
                                } else {
                                    is = getAssets().open("insurerEmailTemplateFR.html");
                                }
                                size = is.available();

                                buffer = new byte[size];
                                is.read(buffer);
                                is.close();

                                String destPath = Constat.getInstance().getPdfPath().replace(".pdf", "_copy" + Constat.getInstance().getAccidentList().get(finalI).getNumAccident() + ".pdf");
                                String destPath1 = Constat.getInstance().getPdfPath().replace(".pdf", "_copy1.pdf");

                                if (insurersPdfStructure[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()].equals("1")) {
                                    List<File> filesList = new ArrayList<>();
                                    if (PdfController.getInstance(activityRef.get()).getAnnexePref()) {
                                        filesList.add(new File(Constat.getInstance().getPdfPath()));
                                        filesList.add(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/annexe.pdf"));
                                    } else {
                                        filesList.add(new File(Constat.getInstance().getPdfPath()));
                                    }
                                    File outputFile = new File(destPath1);
                                    try {
                                        Utilities.mergePdfDocuments(filesList, outputFile);
                                    } catch (DocumentException | IOException e) {
                                        e.printStackTrace();
                                    }

                                } else {
                                    try {
                                        Document document = new Document(PageSize.A4);
                                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destPath1));

                                        document.open();
                                        PdfContentByte cb = writer.getDirectContent();

                                        PdfReader reader = new PdfReader(new FileInputStream(Constat.getInstance().getPdfPath()));
                                        for (int j = 0; j < reader.getNumberOfPages(); j++) {
                                            PdfImportedPage page = writer.getImportedPage(reader, j + 1);
                                            if (j == 0) {
                                                PdfDictionary parameters = new PdfDictionary();
                                                parameters.put(PdfName.MODDATE, new PdfDate());

                                                PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(
                                                        writer, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/annexe.xml",
                                                        "annexe.xml", null, "application/xml", parameters, 0);
                                                fileSpec.put(new PdfName("annexe"), new PdfName("Data"));
                                                writer.addFileAttachment("annexe.xml", fileSpec);

                                                PdfFileSpecification fileSpec1 = PdfFileSpecification.fileEmbedded(
                                                        writer, Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + PACKAGE_NAME + "/xml_def.xsd",
                                                        "xml_def.xsd", null, "application/xml", parameters, 0);
                                                fileSpec.put(new PdfName("xml_def"), new PdfName("Data"));
                                                writer.addFileAttachment("xml_def.xsd", fileSpec1);

                                                PdfArray array = new PdfArray();
                                                array.add(fileSpec.getReference());
                                                array.add(fileSpec1.getReference());
                                                writer.getExtraCatalog().put(new PdfName("AF"), array);
                                            }
                                            cb.addTemplate(page, 0, 0);
                                            document.newPage();
                                        }

                                        document.close();

                                    } catch (DocumentException | IOException e) {
                                        e.printStackTrace();
                                    }
                                }

                                try {
                                    File file1 = new File(destPath);
                                    file1.getParentFile().mkdirs();
                                    Utilities.sealPdf(destPath1, destPath, insurersPasswords[Constat.getInstance().getAccidentList().get(finalI).getCar().getInsurerPosition()]);
                                } catch (DocumentException e) {
                                    e.printStackTrace();
                                }

                                ArrayList<Uri> uris = new ArrayList<Uri>();
                                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N)
                                    uris.add(Uri.fromFile(new File(destPath)));
                                else
                                    uris.add(FileProvider.getUriForFile(context, getApplicationContext().getPackageName() + ".provider", new File(destPath)));

                                str = new String(buffer);
                                str = str.replace("{#CAROWNER}", Constat.getInstance().getAccidentList().get(finalI).getCar().getOwner().getFirstName() + " " + Constat.getInstance().getAccidentList().get(finalI).getCar().getOwner().getLastName());

                                final int i1 = finalI;
                                final int lastInsurerPosition1 = lastInsurerPositionCopy;
                                final String[] toArray1 = toArray;
                                final String str1 = str;
                                final String subject1 = subject;
                                final ArrayList<Uri> uris1 = uris;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (i1 != lastInsurerPosition1) {
                                            Utilities.sendEmails(activityRef.get(), toArray1, null, str1, subject1, uris1, 3);
                                        } else {
                                            Utilities.sendEmails(activityRef.get(), toArray1, null, str1, subject1, uris1, 4);
                                        }
                                        while (!activityRef.get().hasWindowFocus()) {
                                            try {
                                                Thread.sleep(2000);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }
                                });

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    LongOperation lo = new LongOperation(PdfActivity.this, progressRunnable, getResources().getString(R.string.generating),
                            getResources().getString(R.string.generating_email_n_for_insurer, Constat.getInstance().getAccidentList().get(i).getDriver().getFirstName()));
                    lo.execute();
                }
            }
        } else {
            // delete signature image file and redirect user to home screen
            for (int j = 0; j < Constat.getInstance().getAccidentList().size(); j++) {
                File file = new File(Constat.getInstance().getAccidentList().get(j).getSignatureFilePath());
                file.delete();
            }

            // Reset Pdf instance
            PdfController.destroyInstance();

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(getResources().getString(R.string.send_success))
                    .setMessage(getResources().getString(R.string.emails_sended))
                    .setCancelable(false)
                    .setPositiveButton(getResources().getString(R.string.ok_button), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent intent = new Intent(context, MainActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                        }
                    });
            AlertDialog alert = builder.create();
            alert.show();

        }

    }

提前致谢。

1 个答案:

答案 0 :(得分:1)

我可以写一个抽象片段,因为我不理解你的代码,它可以作为指导(如果有帮助)改变你的代码,我会发表答案

声明此类范围

Queue<MyItem> queue = new LinkedList<MyItem>();
//MyItem is a type i think it's what in 'Constat.getInstance().getAccidentList()'
//it should be the type you have to be processed (email and PDF)

您当前的代码(onActivityResult)没有开始处理,只是添加到Queue,并处理队列中的第一项:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    for(int i = 0; i < Constat.getInstance().getAccidentList().size(); i++){
        //add to-be-processed items in the Queue
        queue.add(Constat.getInstance().getAccidentList().get(i));
    }//for loop

    //when loop finish, start processing first item
    MyItem item = queue.remove();
    processItem(item);
}

每次调用onResume()时,检查队列大小,如果为空 可以处理所有项目,或者这是活动第一次打开,因此没有要处理的项目

@Override
protected void onResume()
{
    super.onResume();
    if(queue.size() != 0){
        processItem(queue.remove());
    }//we still have items to process
}

您的实际代码在此处,用于创建PDF,创建电子邮件,发送电子邮件。

private void processItem(MyItem item){
    //start runnable ... to create PDF ...

    //create email body, and start email sending action
}