最近项目中要做一个带进度条的上传文件的功能,学习了asynctask,使用起来比较方便,将几个方法实现就行,另外做了一个很简单的demo,希望能对大家有帮助,在程序中设好文件路径和服务器ip即可。
demo运行截图:
asynctask是抽象类,子类必须实现抽象方法doinbackground(params... p),在此方法中实现任务的执行工作,比如联网下载或上传。asynctask定义了三种泛型类型params,progress和result。
1、params 启动任务执行的输入参数,比如http请求的url,上传文件的路径等;
2、progress 后台任务执行的百分比;
3、result 后台执行任务的最终返回结果,比如string。
asynctask 的执行分为四个步骤,与前面定义的tasklistener类似。每一步都对应一个回调方法,需要注意的是这些方法不应该由应用程序调用,开发者需要做的就是实现这些方法。在任务的执行过程中,这些方法被自动调用。
1、onpreexecute(), 该方法将在执行实际的后台操作前被ui thread调用。可以在该方法中做一些准备工作,如在界面上显示一个进度条。
2、doinbackground(params...), 将在onpreexecute 方法执行后马上执行,该方法运行在后台线程中。这里将主要负责执行那些很耗时的后台计算工作。可以调用 publishprogress方法来更新实时的任务进度。该方法是抽象方法,子类必须实现。
3、onprogressupdate(progress...),在publishprogress方法被调用后,ui thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
4、onpostexecute(result), 在doinbackground 执行完成后,onpostexecute 方法将被ui thread调用,后台的计算结果将通过该方法传递到ui thread.
主进程中使用下面两行开始异步任务:
mtask = new mytask(); mtask.execute(filepath, url);
doinbackground()函数中,params[0]和params[1]本别对应execute()的第一个和第二个变量。
private class mytask extends asynctask<string, integer, string>{ @override protected void onpostexecute(string result) { //最终结果的显示 mtvprogress.settext(result); } @override protected void onpreexecute() { //开始前的准备工作 mtvprogress.settext("loading..."); } @override protected void onprogressupdate(integer... values) { //显示进度 mpgbar.setprogress(values[0]); mtvprogress.settext("loading..." + values[0] + "%"); } @override protected string doinbackground(string... params) { //这里params[0]和params[1]是execute传入的两个参数 string filepath = params[0]; string uploadurl = params[1]; //下面即手机端上传文件的代码 string end = "\r\n"; string twohyphens = "--"; string boundary = "******"; try { url url = new url(uploadurl); httpurlconnection httpurlconnection = (httpurlconnection) url .openconnection(); httpurlconnection.setdoinput(true); httpurlconnection.setdooutput(true); httpurlconnection.setusecaches(false); httpurlconnection.setrequestmethod("post"); httpurlconnection.setconnecttimeout(6*1000); httpurlconnection.setrequestproperty("connection", "keep-alive"); httpurlconnection.setrequestproperty("charset", "utf-8"); httpurlconnection.setrequestproperty("content-type", "multipart/form-data;boundary=" + boundary); dataoutputstream dos = new dataoutputstream(httpurlconnection .getoutputstream()); dos.writebytes(twohyphens + boundary + end); dos .writebytes("content-disposition: form-data; name=\"file\"; filename=\"" + filepath.substring(filepath.lastindexof("/") + 1) + "\"" + end); dos.writebytes(end); //获取文件总大小 fileinputstream fis = new fileinputstream(filepath); long total = fis.available(); byte[] buffer = new byte[8192]; // 8k int count = 0; int length = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); //获取进度,调用publishprogress() length += count; publishprogress((int) ((length / (float) total) * 100)); //这里是测试时为了演示进度,休眠500毫秒,正常应去掉 thread.sleep(500); } fis.close(); dos.writebytes(end); dos.writebytes(twohyphens + boundary + twohyphens + end); dos.flush(); inputstream is = httpurlconnection.getinputstream(); inputstreamreader isr = new inputstreamreader(is, "utf-8"); bufferedreader br = new bufferedreader(isr); @suppresswarnings("unused") string result = br.readline(); dos.close(); is.close(); return "上传成功"; }catch (exception e) { e.printstacktrace(); return "上传失败"; } }
界面中只要一个进度条progressbar 和一个用于显示的textview即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
网友评论