2013-07-20 124 views
0

以下代码具有负责使用特定套接字连接到服务器的线程。连接的想法很好(在一个单独的线程中)。连接建立后,我尝试使用Handler更新主Activity,但它不会更新!使用处理程序更新活动

这里是我的后台线程代码:

public class SocketThread extends Thread { 

private final Socket socket; 
private final InputStream inputStream; 
private final OutputStream outputStream; 
byte[] buffer = new byte[32]; 
int bytes; 


public SocketThread(Socket sock) { 
    socket = sock; 
    InputStream tmpIn = null; 
    OutputStream tmpOut = null; 
    try { 
     tmpIn = socket.getInputStream(); 
     tmpOut = socket.getOutputStream(); 
    } 
    catch (IOException e) {} 
    inputStream = tmpIn; 
    outputStream = tmpOut; 
    EntryActivity.connected = true; 
    buffer = "connect".getBytes(); 
    EntryActivity.UIupdater.obtainMessage(0, buffer.length, -1, buffer).sendToTarget(); 

} 


public void run() { 
    try { 
     while (!Thread.currentThread().isInterrupted()) { 
      bytes = inputStream.read(buffer); 
      EntryActivity.UIupdater.obtainMessage(0, bytes, -1, buffer).sendToTarget(); 
     } 
    } catch (IOException e) { 
    } 
} 
} 

这里是处理:

static Handler UIupdater = new Handler() { 
    public void handleMessage(Message msg) { 
     int numOfBytes = msg.arg1; 
     byte[] buffer = (byte[]) msg.obj; 
     strRecieved = new String(buffer); 
     strRecieved = strRecieved.substring(0, numOfBytes); 
     if (strRecieved.equals("connect")) 
         // Update a TextView 
      status.setText(R.string.connected); 
     else 
         // Do something else; 
    } 
}; 

我核实,已建立连接(使用我的服务器代码),但TextView的没有修改!

+0

在handleMessage中添加Log.d和一些调试消息 – pskink

回答

0

尝试使用handler.sendMessage(handler.obtainMessage(...))而不是handler.obtainMessage(...).sendToTarget()

由于obtainMessage()从全局消息池检索消息,可能是目标设置不正确。

0

请尝试使用下面的示例代码。我希望它能帮助你。

byte[] buffer = new byte[32]; 
static int REFRESH_VIEW = 0; 

public void onCreate(Bundle saveInstance) 
{ 
    RefreshHandler mRefreshHandler = new RefreshHandler(); 

    final Message msg = new Message(); 
    msg.what = REFRESH_VIEW; // case 0 is calling 
    final Bundle bData = new Bundle(); 
    buffer = "connect".getBytes(); 
    bData.putByteArray("bytekey", buffer); 
    msg.setData(bData); 
    mRefreshHandler.handleMessage(msg); // Handle the msg with key and value pair. 
} 

/** 
* RefreshHandler is handler to refresh the view. 
*/ 
static class RefreshHandler extends Handler 
{ 
    @Override 
    public void handleMessage(final Message msg) 
    { 
     switch(msg.what) 
     { 
     case REFRESH_VIEW: 
      final Bundle pos = msg.getData(); 
      final byte[] buffer = pos.getByteArray("bytekey"); 
      String strRecieved = new String(buffer); 
      //Update the UI Part. 
      status.setText("Set whatever you want. " + strRecieved); 
      break; 
     default: 
      break; 
     } 
    } 
};