简体   繁体   中英

Android main thread not waiting for AsyncTask

I'm trying to do some encryptions and show a progress dialog while they are running because depending on the number of encryptions it can take minutes or even hours. I'm trying to measure battery before and after to see how much battery a given number of rounds will drain. My problem is that the main thread isn't waiting for the AsyncTask to finish the encryptions.

Here is what I have so far:

    private void performEncryption(String name) throws InterruptedException {
        int times = this.getNumTimes();

        float batteryPercentageBefore = (new Battery(this)).percentage();
        Log.d("BATTERY", String.valueOf(batteryPercentageBefore));

        long timeBefore = System.currentTimeMillis();

        EncryptionHandler algo = new EncryptionHandler(name);

        (new EncryptionWorker()).execute(new EncryptorParams(algo, times));

        float batteryPercentageAfter = (new Battery(this)).percentage();
        Log.d("BATTERY", String.valueOf(batteryPercentageAfter));

        long timeAfter = System.currentTimeMillis();

        float batteryUsed = batteryPercentageBefore - batteryPercentageAfter;
        Log.d("BATTERY", "Change: " + String.valueOf(batteryUsed));
        long totalTime = timeAfter - timeBefore;

        String text = "It took " + Double.toString(totalTime/1000.0) + " seconds to run " + name
                + " algorithm " + Integer.toString(times) + " times, and it used " + Float.toString(batteryUsed) + "% of battery.";
        Toast.makeText(getApplicationContext(), text,
                Toast.LENGTH_LONG).show();
        lblEncryption.setText(text);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_encryption, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class EncryptionWorker extends AsyncTask<EncryptorParams, Integer, Integer> {
        private ProgressDialog dialog;

        @Override
        public void onPreExecute() {
            super.onPreExecute();

            this.dialog = new ProgressDialog(EncryptionActivity.this);
            this.dialog.setTitle("Encrypting");
            this.dialog.setMessage("Please wait. This may take a while");

            this.dialog.show();
        }

        @Override
        public Integer doInBackground(EncryptorParams... params) {
            for (int i = 0; i < params[0].rounds; i++) {
                try {
                    params[0].encryptor.encrypt("Performs the encryption algorithm", "the name of the encryption algorithm, can be: AES, 3DES, Blowfish");
                } catch (Exception e) {
                    Log.e("EXCEPTION", e.getMessage());
                    return 1;
                }
            }

            return 0;
        }

        @Override
        protected void onPostExecute(Integer result) {
            super.onPostExecute(result);

            this.dialog.dismiss();
        }
    }
}

My problem is that the main thread isn't waiting for the AsyncTask to finish the encryptions

That is the point behind having a background thread in the first place.

Whatever you want to do when the AsyncTask has finished its work, put in onPostExecute() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM