1. 程式人生 > >第0天非同步任務標準寫法

第0天非同步任務標準寫法

第0天非同步任務標準寫法

非同步任務

一.宗旨:不能寫內部類

二.AsyncTask實現網路下載資料,構造傳引數

(1)佈局檔案:activity和item佈局省略:
(2)介面卡程式碼:省略:
(3)activity程式碼:MainActivity.java程式碼

public class Main2Activity extends AppCompatActivity
{ private ArrayList<Bean.DataBean> list = new ArrayList<>();//這裡建立集合 private ListView lv; private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main)
; lv = (ListView) findViewById(R.id.lv); myAdapter=new MyAdapter(this,list);//這裡建立介面卡 lv.setAdapter(myAdapter); new MyTask(lv,list,myAdapter).execute("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1"); } }

(4)AsyncTask程式碼:自定義類繼承AsyncTask,構造傳引數

public class MyTask extends AsyncTask<String,String,String> {
    private ListView listView;
    private ArrayList list;
    private MyAdapter myAdapter;

    public MyTask(ListView listView, ArrayList list, MyAdapter myAdapter) {
        this.listView = listView;
        this.list = list;
        this.myAdapter = myAdapter;
    }

    @Override
    protected String doInBackground(String... strings) {
        //網路請求資料
        StringBuffer sb=new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;
        try {
            URL url=new URL(strings[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(5*1000);
            connection.setConnectTimeout(5*1000);
            if(connection.getResponseCode()==200){
                inputStream  = connection.getInputStream();
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{//最後關流
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                connection.disconnect();
            }
        }
        return sb.toString();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Gson gson=new Gson();
        Bean bean=gson.fromJson(s,Bean.class);
        list.addAll(bean.getData());
        myAdapter.notifyDataSetChanged();
    }
}

三.Thread+Handler+介面回撥實現網路下載資料

(1)佈局檔案:activity和item佈局省略:
(2)介面卡程式碼:省略:
(3)自定義類繼承Thread

//步驟1:自定義類繼承Thread
public class MyThread extends Thread {
    private MyHandler myHandler;
    public MyThread(MyHandler myHandler) {
        this.myHandler = myHandler;
    }
    @Override
    public void run() {
        super.run();
        //網路請求資料
        StringBuffer sb=new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;
        try {
            URL url=new URL("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(5*1000);
            connection.setConnectTimeout(5*1000);
            if(connection.getResponseCode()==200){
                inputStream  = connection.getInputStream();
                byte[] b=new byte[1024];
                int len=0;
                while((len=inputStream.read(b))!=-1){
                    sb.append(new String(b,0,len));
                }
                //handler傳送
                Message message=new Message();
                message.obj=sb.toString();
                myHandler.sendMessage(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{//最後關流
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection!=null){
                connection.disconnect();
            }
        }

    }
}

(4)自定義類繼承Handler並使用介面回撥

//步驟2:自定義類繼承Handler,定義介面
public class MyHandler extends Handler{
    private  MyCallBack callBack;
    public MyHandler(MyCallBack callback) {
        this.callBack=callback;
    }
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
       String json= (String) msg.obj;
       //將json串回調回去
       callBack.onCallBack(json);
    }
    //回撥用的介面
    interface  MyCallBack{
        public void onCallBack(String json);
    }
}

(5)activity程式碼:MainActivity.java程式碼

//步驟3:實現MyCallBack介面
public class Main3Activity extends AppCompatActivity implements MyHandler.MyCallBack {
    private ArrayList<Bean.DataBean> list = new ArrayList<>();//這裡建立集合
    private ListView lv;
    private MyAdapter myAdapter;
    private MyHandler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        myAdapter=new MyAdapter(this,list);//這裡建立介面卡
        lv.setAdapter(myAdapter);
        handler=new MyHandler(this);
        new MyThread(handler).start();
    }
    //回撥介面中的方法
    @Override
    public void onCallBack(String json) {
        Gson gson=new Gson();
        Bean bean=gson.fromJson(json,Bean.class);
        list.addAll(bean.getData());
        myAdapter.notifyDataSetChanged();
    }
}