2013-07-20 121 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; 
     } 
    } 
};