Android中AsyncTask的使用 (包含文件的下载与存储)

时间:2021-05-09 03:32:02

今天看到大神写的相关详解Android中AsyncTask的使用,真的很是佩服,下面我将学习到的AsynTask知识运用到项目中,其中也涉及一些文件的下载与存储到本地

啥都不说了,直接上代码,我将对其进行详细解说,哈哈哈哈哈哈

 public class DownloadAsyncTask extends AsyncTask<String, Float, Integer> {

     // private static final String TAG = "DownloadAsyncTask";

     /****** 下载正常 ******/
private static final int CORRECT = 0;
/****** 404未找到资源 ******/
private static final int NOT_FOUND = 1;
/****** 下载异常 ******/
private static final int ERROR = 2;
/****** 取消下载 ******/
private static final int CANCEL = 3;
/****** SD异常 ******/
private static final int SD_ERROR = 4; private DownloadListener mDownloadListener;
private String mUrl;
private File tempFile; public interface DownloadListener { public void onDownloading(float progress); public void onDownloadComplete(String path); public void onDownloadError(String msg); public void onDownload404(); } public DownloadAsyncTask(String url) {
mUrl = url.replace("-", "%2D");
mUrl = mUrl.replace(" ", "%20");
mUrl = mUrl.replace("+", "%2B");
}
/**
* 获取下载文件
* @param filename
* @return
*/
public static File getDownloadFile(String filename) {
String downloadDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"/Hbdownload";
File dir = new File(downloadDir);
if (!dir.exists()) {
dir.mkdirs();
}
return new File(dir, filename);
}
/**
* 创建下载文件
* @param filename
*/
public static File createDownloadFile(String filename) throws Exception {
String downloadDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Hbdownload";
File dir = new File(downloadDir);
return createFile(dir, filename);
}
// 在指定SD目录创建文件
private static File createFile(File dir, String filename) throws Exception {
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, filename);
file.createNewFile();
return file;
}
/**
* 创建上传文件
* @return
*/
public static File createUploadFile(String filename) throws Exception {
String uploadDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"/Hbdownload";
File dir = new File(uploadDir);
return createFile(dir, filename);
}
@Override
protected Integer doInBackground(String... params) {
tempFile = getDownloadFile(params[0]);
if (tempFile.exists()) return CORRECT;
try {
tempFile =createDownloadFile(params[0]);
} catch (Exception e) {
e.printStackTrace();
return SD_ERROR;
}
FileOutputStream fos = null;
InputStream istream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(mUrl);
HttpResponse response = httpClient.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
istream = response.getEntity().getContent(); fos = new FileOutputStream(tempFile);
long total = response.getEntity().getContentLength();
int readTotal = 0;
byte[] buffer = new byte[1024 * 10];
int length;
while ((length = istream.read(buffer)) > -1) {
if (isCancelled()) {
return CANCEL;
}
fos.write(buffer, 0, length);
readTotal += length;
float progress = readTotal / (total * 1.0f) * 100;
publishProgress(progress);
}
fos.flush();
return CORRECT;
}
if (statusCode == HttpStatus.SC_NOT_FOUND) {
return NOT_FOUND;
}
return ERROR;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (istream != null) {
try {
istream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ERROR;
} @Override
protected void onProgressUpdate(Float... values) {
super.onProgressUpdate(values);
if (mDownloadListener != null) {
mDownloadListener.onDownloading(values[0]);
}
} @Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (mDownloadListener != null) {
switch (result) {
case CORRECT:
mDownloadListener.onDownloadComplete(tempFile.getAbsolutePath());
break;
case NOT_FOUND:
mDownloadListener.onDownload404();
tempFile.delete();
break;
case ERROR:
mDownloadListener.onDownloadError("文件预览出现异常");
tempFile.delete();
break;
case SD_ERROR:
mDownloadListener.onDownloadError("SD卡出现异常,请检查您的设备上是否有SD卡");
tempFile.delete();
case CANCEL:
tempFile.delete();
break;
}
}
} public void setDownloadListener (DownloadListener listener) {
mDownloadListener = listener;
} }

首先在使用DownloadAsyncTask时只需要几个步骤即可

 DownloadAsyncTask task = new DownloadAsyncTask(url);
task.setDownloadListener(new DownloadAsyncTask.DownloadListener() { @Override
public void onDownloading(float progress) { } @Override
public void onDownloadComplete(String path) {
((BaseAppActivity) context).dismissLoadingDialog();
activity.runOnUiThread(new Runnable() {
public void run() { }
});
//下面是成功后的一些步骤
try {
18 if (PPT.contains(type)) {
19 activity.startActivity(FileShowUtils.getPptFileIntent(path));
20 } else if (WORD.contains(type)) {
21 activity.startActivity(FileShowUtils.getWordFileIntent(path));
22 } else if (EXCEL.contains(type)) {
23 activity.startActivity(FileShowUtils.getExcelFileIntent(path));
24 } else if (TEXT.contains(type)) {
25 activity.startActivity(FileShowUtils.getTextFileIntent(path));
26 } else if (PDF.contains(type)) {
27 activity.startActivity(FileShowUtils.getPdfFileIntent(path));
28 } else if (ZIP.contains(type)) {
29
30 } else if (IMAGE.contains(type)) {
31 activity.startActivity(FileShowUtils.getImageFileIntent(path));
32 } else if (AUDIO.contains(type)) {
33 activity.startActivity(FileShowUtils.getAudioFileIntent(path));
34 } else if (VIDEO.contains(type)) {
35 activity.startActivity(FileShowUtils.getVideoFileIntent(path));
36 } else {
37 ((BaseAppActivity) context).showCustomToast("暂时不支持此格式文件的预览");
38 }
39
40
41 } catch (Exception e) {
42 ((BaseAppActivity) context).showCustomToast("您的设备上没有可以打开此类文件的应用");
43 } } @Override
public void onDownloadError(String msg) {
((BaseAppActivity) context).dismissLoadingDialog();
((BaseAppActivity) context).showCustomToast("未知错误");
} @Override
public void onDownload404() {
((BaseAppActivity) context).dismissLoadingDialog();
((BaseAppActivity) context).showCustomToast("未知错误");
}
});
task.execute(filename);

AsyncTask在使用之前首先调用execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。

在DownloadAsyncTask 中我们继承AsyncTask,那么我们将在doInBackground方法中执行较为费时的操作,此方法将接收输入参数和返回计算结果,我们在doinBackground方法中,首先获取下载文件,

如果我们获取的文件在本地存在,那么表示我们的文件本地存在那么就不需要下载,我们可以返回正常的状态,之后我们可以直接使用,如果不存在,则需要我们创建下载文件,将文件通过文件流读写存储到我们建立的文件夹下,成功后则返回状态为正常,在其中过程中我们如果发现不可建立文件等情况则返回sd卡错误的状态,之后我们就可以调用AsyncTask的publishProgress(Progress... values)来更新进度信息

同时调用onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上,最后调用onPostExecute(Result result)方法,对于返回的状态进行操作,在我写的这个DownloadAsyncTask中我使用了接口进行回调,我们可以在回调中进行相关操作,就介绍到这里了,其中代码是参照大神写的,我看过之后感觉很是佩服,因此将自己的一些认知告诉大家,希望大家喜欢!

注意:

在使用的时候,有几点需要格外注意:

1.异步任务的实例必须在UI线程中创建。

2.execute(Params... params)方法必须在UI线程中调用。

3.不要手动调用onPreExecute(),doInBackground(Params... params),onProgressUpdate(Progress... values),onPostExecute(Result result)这几个方法。

4.不能在doInBackground(Params... params)中更改UI组件的信息。

5.一个任务实例只能执行一次,如果执行第二次将会抛出异常。