AsyncTask的使用流程
- 创建一个类继承AsyncTask类,并实现相关方法
- 定义一个接口类,来回调数据
- 在活动中调创建自定义Task类,并执行任务
1. 定义接口类,以实现回调数据
public interface AsyncTaskListener {
//任务执行前
void onPrepare();
//更新任务进度
void onUpdate(Integer... values);
//完成任务,返回结果
void onFinish(String result);
//取消任务
void onCancel();
//返回错误消息
void onError(String msg);
}
2. 创建一个类来继承AsyncTask类,并实现相关方法
//AsyncTask中的类型分别代表<Params,Progress,Result>
public class MyTask extends AsyncTask<String, Integer, String> {
private AsyncTaskListener listener; //回调接口
private boolean isDownloadSuccess; //判断是否下载成功
public MyTask(AsyncTaskListener listener){
this.listener = listener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
listener.onPrepare(); //任务执行前回调
}
@Override
protected String doInBackground(String... params) {
InputStream in = null;
OutputStream out = null;
/**创建一个文件用来保存下载文件**/
String filePath = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(filePath);
if (!file.exists()){
file.mkdir();
}
File imageFile = new File(filePath + "test.mp3");
/**创建一个文件用来保存下载文件**/
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(6000);
connection.setRequestMethod("POST");
//注意:为了后期获取文件长度
connection.setRequestProperty("Accept-Encoding", "identity");
//响应失败,则返回,并回调错误
if (connection.getResponseCode() != 200){
Log.d("tag", "connect fail");
listener.onError("Connect Fail");
return null;
}
in = connection.getInputStream();
out = new FileOutputStream(imageFile);
//获取到文件长度
int fileLength = connection.getContentLength();
int count = 0;
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buf)) != -1){
out.write(buf, 0, bytesRead);
count += bytesRead;
//发布更新进度
publishProgress((int)(((double)count/fileLength)*100), fileLength);
}
out.flush();
//标识下载成功
isDownloadSuccess = true;
} catch (IOException e) {
e.printStackTrace();
listener.onError(e.getMessage());
} finally {
IoUtil.close(in);
IoUtil.close(out);
}
//返回文件路径
return imageFile.getAbsolutePath();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
listener.onUpdate(values); //回调进度
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (isDownloadSuccess){
listener.onFinish(s); //当文件下载成功后,才返回结果
}
}
@Override
protected void onCancelled() {
super.onCancelled();
listener.onCancel();
}
}
3. 创建自定义类,执行任务
public class AsyncTaskActivity extends AppCompatActivity {
private ProgressDialog progressDialog; //对话框式进度显示
private Button btn_download;
private String url = "http://programmerguru.com/android-tutorial/wp-content/uploads/2014/01/jai_ho.mp3"; //测试url
private String imageFilePath; //下载保存的文件路径
private boolean permissionAllowed = false; //权限设置
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_task);
btn_download = (Button) findViewById(R.id.btn_download);
btn_download.setOnClickListener(new MyOnClickListener());
//请求权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
} else {
permissionAllowed = true;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 0:{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
permissionAllowed = true;
}
}
}
}
class MyOnClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
if (permissionAllowed){
downloadImage();
}
}
}
//下载文件
private void downloadImage(){
final MyTask mTask = new MyTask(new AsyncTaskListener() {
@Override
public void onPrepare() {
//开始前,设置进度对话框
btn_download.setEnabled(false);
progressDialog = new ProgressDialog(AsyncTaskActivity.this);
progressDialog.setTitle("下载中");
progressDialog.show();
}
@Override
public void onUpdate(Integer... values) {
//更新进度
String unit = "KB";
if (values[1] > 1024*1024){
values[1] /= 1024;
unit = "MB";
}
progressDialog.setMessage("共" + String.valueOf(values[1]/1024) + unit + ", 已下载" + String.valueOf(values[0]) + "%");
}
@Override
public void onFinish(String result) {
//返回结果
btn_download.setEnabled(true);
progressDialog.dismiss();
Toast.makeText(AsyncTaskActivity.this, "下载成功", Toast.LENGTH_LONG).show();
imageFilePath = result;
Log.d("tag","imageFilePath:" + imageFilePath);
}
@Override
public void onCancel() {
}
@Override
public void onError(final String error) {
//发送错误,返回错误,注意:这里是非UI线程内
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(AsyncTaskActivity.this, error, Toast.LENGTH_LONG).show();
}
});
}
});
//执行任务
mTask.execute(url);
}
}