<p>AsyncTask,是android提供的轻量级的异步类,可以直接继承AsyncTask,在类中实现异步操作,并提供接口反馈当前异步执行的程度(可以通过接口实现UI进度更新),最后反馈执行的结果给UI主线程.</p><p>使用的优点:</p><p>l 简单,快捷</p><p>l 过程可控</p><p>使用的缺点:</p><p>l 在使用多个异步操作和并需要进行Ui变更时,就变得复杂起来.</p><p>2 )Handler异步实现的原理和适用的优缺点</p><p></p><p>AsyncTask介绍</p><p>Android的AsyncTask比Handler更轻量级一些,适用于简单的异步处理。</p><p>首先明确Android之所以有Handler和AsyncTask,都是为了不阻塞主线程(UI线程),且UI的更新只能在主线程中完成,因此异步处理是不可避免的。</p><p>Android为了降低这个开发难度,提供了AsyncTask。AsyncTask就是一个封装过的后台任务类,顾名思义就是异步任务。</p><p>AsyncTask直接继承于Object类,位置为android.os.AsyncTask。要使用AsyncTask工作我们要提供三个泛型参数,并重载几个方法(至少重载一个)。</p><p>AsyncTask定义了三种泛型类型 Params,Progress和Result。</p><p>Params 启动任务执行的输入参数,比如HTTP请求的URL。</p><p>Progress 后台任务执行的百分比。</p><p>Result 后台执行任务最终返回的结果,比如String。</p><p>使用过AsyncTask 的同学都知道一个异步加载数据最少要重写以下这两个方法:</p><p>doInBackground(Params…) 后台执行,比较耗时的操作都可以放在这里。注意这里不能直接操作UI。此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。</p><p>onPostExecute(Result) 相当于Handler 处理UI的方式,在这里面可以使用在doInBackground 得到的结果处理操作UI。 此方法在主线程执行,任务执行的结果作为此方法的参数返回</p><p>有必要的话你还得重写以下这三个方法,但不是必须的:</p><p>onProgressUpdate(Progress…) 可以使用进度条增加用户体验度。 此方法在主线程执行,用于显示任务执行的进度。</p><p>onPreExecute() 这里是最终用户调用Excute时的接口,当任务执行之前开始调用此方法,可以在这里显示进度对话框。</p><p>onCancelled() 用户调用取消时,要做的操作</p><p>使用AsyncTask类,以下是几条必须遵守的准则:</p><p>Task的实例必须在UI thread中创建;</p><p>execute方法必须在UI thread中调用;</p><p>不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法;</p><p>该task只能被执行一次,否则多次调用时将会出现异常;</p><p>下面给出一个我写的小demo,仅供大家参考,运行结果如图:</p><p></p><p><img src="/up_pic/201812/171037188990.png" title="171037188990.png"/></p><p><img src="/up_pic/201812/171037183654.png" title="171037183654.png"/></p><p><img src="/up_pic/201812/171037188993.png" title="171037188993.png"/></p><p>首先是AysncTask类:</p><pre class="brush:java;toolbar:false">packagely.asynctasktest; importandroid.content.Context; importandroid.os.AsyncTask; importandroid.widget.TextView; importandroid.widget.Toast; /** *Createdbykfbmac3on16/7/8. */ /* AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params, Progress和Result的类型,如AsyncTask&lt;void,inetger,void&gt;: Params是指调用execute()方法时传入的参数类型和doInBackgound()的参数类型 Progress是指更新进度时传递的参数类型,即publishProgress()和onProgressUpdate()的参数类型 Result是指doInBackground()的返回值类型 doInBackgound()这个方法是继承AsyncTask必须要实现的,运行于后台,耗时的操作可以在这里做 publishProgress()更新进度,给onProgressUpdate()传递进度参数 onProgressUpdate()在publishProgress()调用完被调用,更新进度 */ publicclassUpdateTextTaskextendsAsyncTask&lt;void,integer,string&gt;{ privateContextcontext; privateStringurl; privateStringpostValue; privateTextViewtext; UpdateTextTask(Contextcontext,Stringstring,StringpostValue,TextViewtext){ this.context=context; this.url=string; this.postValue=postValue; this.text=text; } /** *运行在UI线程中,在调用doInBackground()之前执行 *该方法运行在UI线程当中,并且运行在UI线程当中可以对UI空间进行设置 */ @Override protectedvoidonPreExecute(){ Toast.makeText(context,&quot;开始执行&quot;,Toast.LENGTH_SHORT).show(); } /** *后台运行的方法,可以运行非UI线程,可以执行耗时的方法 *这里的Void参数对应AsyncTask中的第一个参数 *这里的String返回值对应AsyncTask的第三个参数 *该方法并不运行在UI线程当中,主要用于异步操作,所有在该方法中不能对UI当中的空间进行设置和修改 *但是可以调用publishProgress方法触发onProgressUpdate对UI进行操作 */ @Override protectedStringdoInBackground(Void...params){ inti=0; while(i&lt;10){ i++; //publishProgress更新进度,给onProgressUpdate()传递进度参数 publishProgress(i); try{ Thread.sleep(1000); }catch(InterruptedExceptione){ } } Stringresult=Common.postGetJson(url,postValue); //第三个参数为String所以此处return一个String类型的数据 returnresult; } /** *这里的String参数对应AsyncTask中的第三个参数(也就是接收doInBackground的返回值) *运行在ui线程中,在doInBackground()执行完毕后执行,传入的参数为doInBackground()返回的结果 */ @Override protectedvoidonPostExecute(Stringi){ Toast.makeText(context,i,Toast.LENGTH_SHORT).show(); text.setText(i); } /** *在publishProgress()被调用以后执行,publishProgress()用于更新进度 *这里的Intege参数对应AsyncTask中的第二个参数 *在doInBackground方法当中,,每次调用publishProgress方法都会触发onProgressUpdate执行 *onProgressUpdate是在UI线程中执行,所有可以对UI空间进行操作 */ @Override protectedvoidonProgressUpdate(Integer...values) { //第二个参数为Int text.setText(&quot;&quot;+values[0]); } } &lt;/void,integer,string&gt;&lt;/void,inetger,void&gt;</pre><p>接下来是发送http请求的方法:</p><pre class="brush:xml;toolbar:false">packagely.asynctasktest; importandroid.util.Log; importjava.io.ByteArrayOutputStream; importjava.io.DataOutputStream; importjava.io.InputStream; importjava.net.HttpURLConnection; importjava.net.URL; importjava.util.List; importjava.util.Map; /** *Createdbykfbmac3on16/5/20. */ publicclassCommon{ publicstaticStringpostGetJson(Stringurl,Stringcontent){ try{ URLmUrl=newURL(url); HttpURLConnectionmHttpURLConnection=(HttpURLConnection)mUrl.openConnection(); //设置链接超时时间 mHttpURLConnection.setConnectTimeout(15000); //设置读取超时时间 mHttpURLConnection.setReadTimeout(15000); //设置请求参数 mHttpURLConnection.setRequestMethod(&quot;POST&quot;); //添加Header mHttpURLConnection.setRequestProperty(&quot;Connection&quot;,&quot;Keep-Alive&quot;); //接收输入流 mHttpURLConnection.setDoInput(true); //传递参数时需要开启 mHttpURLConnection.setDoOutput(true); //Post方式不能缓存,需手动设置为false mHttpURLConnection.setUseCaches(false); mHttpURLConnection.connect(); DataOutputStreamdos=newDataOutputStream(mHttpURLConnection.getOutputStream()); StringpostContent=content; dos.write(postContent.getBytes()); dos.flush(); //执行完dos.close()后,POST请求结束 dos.close(); //获取代码返回值 intrespondCode=mHttpURLConnection.getResponseCode(); Log.d(&quot;respondCode&quot;,&quot;respondCode=&quot;+respondCode); //获取返回内容类型 Stringtype=mHttpURLConnection.getContentType(); Log.d(&quot;type&quot;,&quot;type=&quot;+type); //获取返回内容的字符编码 Stringencoding=mHttpURLConnection.getContentEncoding(); Log.d(&quot;encoding&quot;,&quot;encoding=&quot;+encoding); //获取返回内容长度,单位字节 intlength=mHttpURLConnection.getContentLength(); Log.d(&quot;length&quot;,&quot;length=&quot;+length); ////获取头信息的Key //Stringkey=mHttpURLConnection.getHeaderField(idx); //Log.d(&quot;key&quot;,&quot;key=&quot;+key); //获取完整的头信息Map Map&lt;string,string=&quot;&quot;&gt;&gt;map=mHttpURLConnection.getHeaderFields(); if(respondCode==200){ //获取响应的输入流对象 InputStreamis=mHttpURLConnection.getInputStream(); //创建字节输出流对象 ByteArrayOutputStreammessage=newByteArrayOutputStream(); //定义读取的长度 intlen=0; //定义缓冲区 bytebuffer[]=newbyte[1024]; //按照缓冲区的大小,循环读取 while((len=is.read(buffer))!=-1){ //根据读取的长度写入到os对象中 message.write(buffer,0,len); } //释放资源 is.close(); message.close(); //返回字符串 Stringmsg=newString(message.toByteArray()); Log.d(&quot;Common&quot;,msg); returnmsg; } return&quot;fail&quot;; }catch(Exceptione){ return&quot;error&quot;; } } }</pre><p>MainActivity:</p><pre class="brush:java;toolbar:false">packagely.asynctasktest; importandroid.support.v7.app.AppCompatActivity; importandroid.os.Bundle; importandroid.view.View; importandroid.widget.Button; importandroid.widget.TextView; importjava.net.URLEncoder; publicclassMainActivityextendsAppCompatActivity{ privateButtonbtn; privateTextViewtext; privateStringurl=&quot;https://192.168.24.104:3000/users&quot;; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn=(Button)findViewById(R.id.btn); text=(TextView)findViewById(R.id.text); btn.setOnClickListener(newView.OnClickListener(){ @Override publicvoidonClick(Viewv){ Update(); } }); } privatevoidUpdate(){ try{ Stringvalue=URLEncoder.encode(&quot;username&quot;,&quot;UTF-8&quot;)+&quot;=&quot;+ URLEncoder.encode(&quot;anwei&quot;,&quot;UTF-8&quot;)+&quot;&amp;&quot;+ URLEncoder.encode(&quot;userfullname&quot;,&quot;UTF-8&quot;)+&quot;=&quot;+ URLEncoder.encode(&quot;安威&quot;,&quot;UTF-8&quot;); UpdateTextTaskupdatetext=newUpdateTextTask(this,url,value,text); updatetext.execute(); }catch(Exceptione){ text.setText(&quot;error&quot;); } } }</pre><p>需要注意的问题依然是要在AndroidManifest.xml文件中添加网络权限:</p><pre class="brush:xml;toolbar:false">&lt;uses-permissionandroid:name=&quot;android.permission.INTERNET&quot;&gt;&lt;/uses-permission&gt;</pre><p>文中的url是我用node.js写的一个简单后台,接收到post信息后在MongoDB中查找数据并返回,后台接收到的数据如图:</p>
RangeTime:0.008002s
RangeMem:215.6 KB
返回顶部 留言