当前位置: 移动技术网 > 移动技术>移动开发>Android > android AsynTask处理返回数据和AsynTask使用get,post请求

android AsynTask处理返回数据和AsynTask使用get,post请求

2019年07月24日  | 移动技术网移动技术  | 我要评论

android是一个单线程模型,android界面(ui)的绘制都只能在主线程中进行,如果在主线程中进行耗时的操作,就会影响ui的绘制和事件的响应。所以在android规定,不可在主线中进行耗时操作,否则将发生程序无响应(anr)问题。

解决办法:开启新的线程进行耗时操作

开启新的线程可以new thread() 或实现runnable接口

什么要使用asynctask呢?

如果是使用thread的run()方法,run()结束之后没有返回值。所以必须要自己建立通信机制

asynctask将所有的线程通信都封装成回调函数,调用逻辑容易书写。尤其是在异步处理结束之后,有回调函数进行收尾处理。咳咳,程序员都懒的么

android给我们提供的一个轻量级的用于处理异步任务的类:asynctask   当然是那个简单就用那个咯

最后还有一点就是:android 4.0后禁止在ui线程中执行网络操作~不然会报:android.os.networkonmainthreadexception

什么是asynctask(原谅宝宝偷的图   嘿嘿  不过真的解释的很清楚呢)

注意:

 task的实例必须在ui thread中创建

 execute方法不惜在ui thread中创建

 task只能被执行一次 多次调用时会出现异常

通用asynctask 以及在主线程中使用网络请求回返的数据

   通用asynctask是什么意思呢 发送不同的请求返回不同类型的数据 难道要一个类型写个asynctask 岂不是麻烦死咯

   还有一种情况  我们通过异步任务得到了一个对象然后在一下行立刻使用这个对象逻辑完全没问题但是运行之后会报空指针异常。这是怎么回事呢?       

   asycntask开始了一个新的线程,但是主线程并没有停止还在继续运行,马上就使用这个对象,而你新开的线程可能正在访问网络这个对象为空

   你无法确定asycntask什么时候才能获取到数据,网快嗖的一下就好了,网慢就要等好久。

看一个简略的小例子

首先呢  我们使用异步任务的时候要处理不同类型的数据把这个http设置泛型类第三个参数返回值类型设置为泛型不管你是什么类型的数据全部ok

我又写了一个接口作为http的属性  在onpostexecute方法调用其中的onresponse方法在test中实现接口

这个接口的作用完全可以理解为一个监听事件 checkbox的改变监听触发条件是 是否选中这个接口监听是否有数据  完成网络访问有数据的时候就调用

我们在主线程中完成接口的实现已经在主线程中实现了返回来的数据还不是任君宰割阿~~~~~

 public class http<t> extends asynctask<string,void,t> {
 private onresponselistener<t> listener;
 public void setlistener(onresponselistener<t> listener) {
 this.listener = listener;
 }
 @override
 protected t doinbackground(string... params) {
 return null;
 }
 @override
 protected void onpostexecute(t t) {
 super.onpostexecute(t);
 if (listener!=null){
  listener.onresponse(t);
 }
 }
 //接口 类似一个监听事件
 public interface onresponselistener<t>{
 void onresponse(t t);
 }
}
//获取数据的测试类
public class test {
 //要获取的user对象
 private user user1=null;
 public void get(){
 //创建网络访问实例
 http<user> http=new http<user>();
 //重写接口
 http.setlistener(new http.onresponselistener<user>() {
  @override
  public void onresponse(user user) {
  user1=user;
  }
 });
 http.execute("xxx.balabala.com");
 }
}

在发送请求的时候很容易就带个参数,请求的方式呢 无非就是get,post 两者的区别呢大白话的说get不安全参数通过url直接传过去post安全参数加密一下子

下面贴一下asynctask在get和post请求时核心代码doinbackground方法

get

protected t doinbackground(string... params) {
 //网络连接对象
 httpurlconnection connection=null;
 //输入流 获取网络数据
 inputstream is=null;
 //字节数组输出流
 bytearrayoutputstream bos=null;
 try {
  //获取网络连接对象
  connection=(httpurlconnection) new url(params[0]).openconnection();
  //设置get请求 必须大写
  connection.setrequestmethod("get");
  //获取网络请求码 200 400 500之类 不懂百度
  int code=connection.getresponsecode();
  if(code==200){
  //获取流
  is=connection.getinputstream();
  //临时字节数组
  byte [] b=new byte[1024];
  int len=-1;
  bos=new bytearrayoutputstream();
  while ((len=is.read(b))!=-1){
   //写入数据
   bos.write(b,0,len);
  }
  string json=bos.tostring("utf-8");
  t t=json.parseobject(json,type);
  return t;
  }else{
  log.e("error","网络访问失败==========="+code);
  }
 } catch (ioexception e) {
  e.printstacktrace();
 }finally {
  try {
  if (bos!=null){
   bos.close();
  }
  if (is!=null){
   is.close();
  }
  } catch (ioexception e) {
  e.printstacktrace();
  }
  if (connection!=null){
  connection.disconnect();
  }
 }
 return null;
 }

post

post和get的区别  就是post多了一段处理参数的代码

protected t doinbackground(string... params) {
 //分割url 分为地址和参数两部分
 string[] strarr=params[0].split("\\?");
 httpurlconnection connection=null;
 //输出流
 outputstream os=null;
 //输入流
 inputstream is=null;
 bytearrayoutputstream bos=null;
 try {
  connection=(httpurlconnection) new url(strarr[0]).openconnection();
  connection.setrequestmethod("post");
  //设置允许输入 输出 默认值true 不写也可以
  connection.setdooutput(true);
  connection.setdoinput(true);
  os=connection.getoutputstream();
  //把参数写入
  os.write(strarr[1].getbytes("utf-8"));
  os.close();
  int code=connection.getresponsecode();
  if(code==200){
  is=connection.getinputstream();
  byte [] b=new byte[1024];
  int len=-1;
  bos=new bytearrayoutputstream();
  while ((len=is.read(b))!=-1){
   bos.write(b,0,len);
  }
  string json=bos.tostring("utf-8");
  t t=json.parseobject(json,type);
  return t;
  }else{
  log.e("error","网络访问失败==========="+code);
  }
 } catch (ioexception e) {
  e.printstacktrace();
 }finally {
  try {
  if (bos!=null){
   bos.close();
  }
  if (is!=null){
   is.close();
  }
  } catch (ioexception e) {
  e.printstacktrace();
  }
  if (connection!=null){
  connection.disconnect();
  }
 }
 return null;
 }

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网