AsyncTask中的4个回调
onPreExecute(),在doInBackground(Params...)之前运行在UI线程中
onPostExecute(Result),在doInBackground(Params...)之后运行在UI线程中
onProgressUpdate(Progress...),在publishProgress(Progress...)被调用后运行在UI线程中
doInBackground(Params...),运行在子线程中,这个函数可以调用publishProgress以发布更新到UI线程
示例如下
public class Md5AsyncTask extends AsyncTask<String, Long, String> { @Override protected void onPreExecute() { super.onPreExecute(); Log.d(TAG, "onPreExecute() called"); tv1.setText("已执行"); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d(TAG, "onPostExecute(String) called"); tv3.setText("已结束"); tvResult.setText(s); } @Override protected void onProgressUpdate(Long... values) { super.onProgressUpdate(values); tv2.setText(values[0] + "%"); } @Override protected String doInBackground(String... strings) { File file = new File(strings[0]); long fileSize = file.length(); try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[10 * 1024 * 1024]; int numberOfBytesRead; long totalNumberOfBytesRead = 0; while ((numberOfBytesRead = bis.read(buffer)) != -1) { md5.update(buffer, 0, numberOfBytesRead); totalNumberOfBytesRead += numberOfBytesRead; publishProgress(totalNumberOfBytesRead * 100 / fileSize); } StringBuilder result = new StringBuilder(); byte[] digested = md5.digest(); for (byte e : digested) { String hexStr = Integer.toHexString(e & 255); if (hexStr.length() == 1) result.append('0'); result.append(hexStr); } return result.toString(); } catch (IOException | NoSuchAlgorithmException ex) { Log.e(TAG, null, ex); return null; } } }
new Md5AsyncTask().execute(filename);