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