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

 //主线程中接收子线程发送的消息并处理
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是需要发送的数据。可以是intstringobject等。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进行网络访问,希望对大家有所帮助。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(创建子线程对Android进行网络访问)