java - Android主线程不等待AsyncTask

标签 java android multithreading concurrency android-asynctask

我正在尝试进行一些加密并在它们运行时显示进度对话框,因为根据加密数量,可能需要几分钟甚至几小时。我正在尝试测量之前和之后的电池电量,看看给定的轮数会消耗多少电池。我的问题是主线程没有等待 AsyncTask 完成加密。

这是我到目前为止所拥有的:

    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

这就是后台线程的首要意义。

AsyncTask完成其工作时,无论您想做什么,都可以放入onPostExecute()

关于java - Android主线程不等待AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29956478/

相关文章:

java - 具有多个分隔符的 Split()(不起作用)

java.lang.IllegalStateException : Could not execute method of the activity, 如何解决?

android - Android Market 中的应用程序与设备不兼容

android - Flutter 运行发布失败 : Minimum supported Gradle version is 5. 6.4。当前版本是 5.6.2

python - 如何在执行任务时更新进度条

java - 如何使光标默认出现在 JTextField 中?

Java优先级队列和可比较的接口(interface)

WPF:从后台线程更新 UI 的问题

JAVA获取线程中可运行对象

java - 初始化对象数组时的默认值是什么