2017-04-12 42 views
2

我有兩個類Thread類設置文本,一個是活動的,一種是Thread類:從活動

活動:

public class MainActivity extends AppCompatActivity { 

    ObjectInputStream inFromServer = null; 
    ObjectOutputStream outToServer=null; 
    Socket clientSocket = null; 
    String userName; 

    EditText message; 
    static TextView textView; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 

     message = (EditText)findViewById(R.id.txtMessage); 
     textView = (TextView)findViewById(R.id.textView); 

     try { 
      clientSocket = new Socket("10.0.0.41", 10002); 

      outToServer = 
        new ObjectOutputStream(clientSocket.getOutputStream()); 

      inFromServer = 
        new ObjectInputStream((clientSocket.getInputStream())); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     ReceiveMessages receiveMessages = new ReceiveMessages(inFromServer); 
     receiveMessages.start(); 
    } 

    public void onClickSend(View view) throws IOException { 
     outToServer.writeObject("Eliran!" + message.getText().toString()); 
    } 

    public void btnUserName(View view) throws IOException { 
     EditText editText = (EditText)findViewById(R.id.userName); 
     userName = editText.getText().toString(); 
     outToServer.writeObject(userName + "!"); 
    } 
} 

Thread類:

public class ReceiveMessages extends Thread { 

    ObjectInputStream inFromServer = null; 

    public ReceiveMessages(ObjectInputStream inFromServer) 
    { 
     this.inFromServer = inFromServer; 
    } 

    public void run() { 
     try { 
      while (true) { 
       String message = (String) inFromServer.readObject(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我想在Thread類的活動的文本視圖中設置文本。 我該怎麼辦? InflateLayout沒有幫助我想。

+0

您不能使用Thread類更改UI元素,您應該使用AsyncTask。看看這個鏈接:http://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread – Michael

回答

0

我會通過創建一個回調來解決這個問題,該回調在從機翼接收到字符串時被調用。

interface ReceiveMessageListener { 
    void onMessageReceived (String message); 
} 

然後讓我的Activity實現接口並在onMessageReceived回調中設置文本。

@Override 
public void onMessageReceived (String message) { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      textView.setText(message); 
     } 
    }); 
} 

您還必須更改MessageReceive類的構造函數以接收MessageReceiveListener。

從你的活動:

ReceiveMessages receive = new ReceiveMessages(input, this); 
0

只有UI線程可以與UI元素(如TextView的)進行交互。嘗試使用runOnOiThread或mainHandler.post()