• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

Android中创建子线程进行网络访问

互联网 diligentman 2小时前 1次浏览
 //主线程中接收子线程发送的消息并处理
private Handler handler=new Handler(){
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg){
            try {
                switch (msg.what){
                    case 0:
                        String Listeningresponse= msg.getData().getString("Listeningdate");
                    case 1:
                        String response = msg.getData().getString("date");
                    case 2:
                        vsnfilename=msg.getData().getString("vsndate");
                    default:
                        Log.e(TAG, " handler fail in send" );
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }
    };

上面代码是在主线程中接收子线程发送的消息,根据消息标识处理后续操作。下面是子线程代码:

开启子线程服务:new Thread(runnable).start();

子线程执行的任务:

 Runnable runnabletday = new Runnable(){
        @Override
        public void run() {
            try {
                //String url=ResourceMethod.UrlSplicingMinute();
                String url2=ResourceMethod.UrlSplicingDay();
                hadata=getDateFromSever(url2);
                Message msg = new Message();
                Bundle bundle =new Bundle();
                bundle.putString("date", hadata);// 这是数据标志,在接收的时候方便辨认
                msg.setData(bundle);
                msg.what = 1;
                handler.sendMessage(msg);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

代码    Bundle bundle =new Bundle();      bundle.putString("date", hadata)中data是数据标识,hadata是需要发送的数据。可以是int,string,object等。msg.what = 1是设置的消息标识位,在接收消息的时候作为区分消息。

hadata=getDateFromSever(url2)是访问url2获取数据的方法:具体实现如下:

//进行http请求并获取返回的数据
    public String getDateFromSever(String url) {
        try {
            OkHttpClient client = new OkHttpClientFactory().getInstance();
            Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Response response = client.newCall(request).execute();
            Log.d(TAG, "Ipaws response="+response);
            String responseData = response.body().string();
            if (response.isSuccessful()) {
                return responseData;
            }else {
                Log.d(TAG, "responseData: error");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


程序员灯塔
转载请注明原文链接:Android中创建子线程进行网络访问
喜欢 (0)