0

我有一个 AsyncTask 连接到网络资源并尝试从资源中读取数据。这个资源可以随时发送数据,所以我需要套接字在后台。当我在初始连接上收到响应时,我收到消息,它显示在 MainActivity 上的 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);
        }

}
4

1 回答 1

0

只需将您DisplayData(new String(data,"UTF-8"));移至 OnProgressUpdate(),如果您仍有问题,请按照教程进行操作。

于 2013-06-13T16:20:51.050 回答