AsyncTask套接字错误

时间:2013-06-13 15:47:35

标签: android sockets android-asynctask

我有一个AsyncTask,它连接到网络资源并尝试从资源中读取数据。 此资源可以随时发送数据,因此我需要套接字在后台。 当我在初始连接上得到响应时,我收到消息,并在MainView上的TextView上显示,但是当服务器发送另一条消息时,我得到 错误:

06-13 15:46:01.932: I/AsyncTask(1818): doInBackground: Exception Details : Only the original thread that created a view hierarchy can touch its views.

以下是我的代码:

public class Client extends AsyncTask<Void, byte[], Boolean> {

        private String SvrAddr = svradr;
        private int Svrport = port;
        private InputStream input;
        private OutputStream output;    
        private Socket nSocket;


        @Override
        protected Boolean doInBackground(Void... params){
            boolean rslt = false;
            try{
                Log.i("AsyncTask", "doInBackground: Creating Socket");
                SocketAddress sockad = new InetSocketAddress(SvrAddr,Svrport);
                nSocket = new Socket();
                nSocket.connect(sockad,5000);
                if(nSocket.isConnected()){
                    input =  nSocket.getInputStream();
                    output = nSocket.getOutputStream();
                    Log.i("AsyncTask","doInBackground: Socket created.. Streams gotten");
                    byte[] buffer= new byte[4096];
                    int read = input.read(buffer,0,4096);
                    while(read!=-1){
                        byte[] data = new byte[read];
                        System.arraycopy(buffer, 0, data,0,read);
                        Log.i("AsyncTask","doInBackgroiund: got data :" + new String(data,"UTF-8"));
                        DisplayData(new String(data,"UTF-8"));
                        read =  input.read(buffer,0,4096);
                    }
                }
            }catch(IOException ioe){
                Log.i("AsyncTask","doInBackground: IO Exception");
                rslt=true;
            }catch(Exception e){
                Log.i("AsyncTask","doInBackground: Exception Details : " + e.getMessage());
                rslt = true;
            }finally{


                try{
                    input.close();
                    output.close(); 
                    nSocket.close();
                }catch(IOException ioe){

                }catch(Exception e){
                    Log.i("AsyncTask","doInBackground: Exception");
                    rslt = true;
                }
                Log.i("AsyncTask","doInBackground: Completed");
            }
            return rslt;
        }

        private void DisplayData(String msg){               
            TextView t = (TextView) findViewById(R.id.textView1);
            t.setText(msg);
        }

}

1 个答案:

答案 0 :(得分:0)

只需将DisplayData(new String(data,"UTF-8"));移至OnProgressUpdate(),如果仍有问题,请关注tutorial