[android] 兩種非同步方式

來源:互聯網
上載者:User

標籤:

使用AsyncTask開啟子線程擷取伺服器資料,更新介面UI

 

    /**     * 非同步任務     *      * @author taoshihan     *      */    public class HttpAsyncTask extends AsyncTask<String, Void, String> {        /**         * 在執行背景工作之前執行         */        @Override        protected void onPreExecute() {            String netInfo = NetUtils.getNetworkInfo(context);            if ("no".equals(netInfo)) {                Toast.makeText(context, "網路連接失敗", 0).show();            } else if ("wifi".equals(netInfo)) {                Toast.makeText(context, "wifi串連", 0).show();            } else if ("mobile".equals(netInfo)) {                Toast.makeText(context, "手機流量串連", 0).show();            }        }        /**         * 後台運行,耗時的操作都放在這裡,相當於Thread的run方法         */        @Override        protected String doInBackground(String... params) {            // TODO Auto-generated method stub            return null;        }        /**         * 在執行背景工作之後,可以在這更改UI介面,相當於Handler裡面的處理方法         */        @Override        protected void onPostExecute(String result) {            // TODO Auto-generated method stub            super.onPostExecute(result);        }    }

 

 

 

使用Thread和Handler非同步擷取資訊

 

    /**     * 使用線程和Handler     * @author taoshihan     *     */    public class HttpHandler extends Handler{        @Override        public void handleMessage(Message msg) {            //處理Message        }    }    public class HttpThread extends Thread{        @Override        public void run() {            //發送Message            new HttpHandler().sendMessage(new Message());        }    }

 

new HttpThread().start();new HttpAsyncTask().execute("htp://www.baidu.com");

 

 

[android] 兩種非同步方式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.