ネットワーク リソースに接続し、リソースからデータを読み取ろうとする 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);
}
}