我正在尝试编写代码来每秒更新消息的服务器。邮件然后显示在文本视图中。如果我不更改文本视图中的文本,它运行良好。如果我尝试更改线程上的textview,它会崩溃。如果我改变它不在线程工作正常。我怎样才能从一个线程chnage TextViews文本?
我假设线程无法访问主线程的内存?如何使用刚刚通过互联网加载的文本在视图中设置文本?
在下面的代码中,我有一个线程,做一个无限循环与睡眠。它调用一个名为SendMessage的方法。发送消息通过互联网载入文本,最后尝试使用它更新视图。发生这种情况时会导致异常。
代码:
public class cChat extends cBase implements OnClickListener {
/** Called when the activity is first created. */
TextView mUsers;
TextView mComments;
int i=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat);
mUsers=(TextView) findViewById(R.id.viewusers);;
mComments=(TextView) findViewById(R.id.viewchats);;
Thread thread = new Thread()
{
@Override
public void run() {
try {
int t=0;
while(true)
{
SendMessage();
sleep(1000*5);
t++;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
public void onClick(View v) {
} // end function
// send a uypdate message to chat server
// return reply in string
void SendMessage()
{
try {
URL url = new URL("http://50.63.66.138:1044/update");
System.out.println("make connection");
URLConnection conn = url.openConnection();
// set timeouts to 5 seconds
conn.setConnectTimeout(1000*5);
conn.setReadTimeout(5*1000);
conn.setDoOutput(true);
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// String line;
String strUsers=new String("");
String strComments=new String("");
String line=new String();
int state=0;
while ((line= rd.readLine() ) != null) {
switch(state){
case 0:
if (line.contains("START USER"))
state=1;
if (line.contains("START COMMENTS"))
state=2;
break;
case 1:
if (line.contains("END USER"))
state=0;
else
{
strUsers+=line;
strUsers+="\n";
}
break;
case 2:
if (line.contains("END COMMENTS"))
state=0;
else {
strComments+=line;
strComments+="\n";
}
break;
} // end switch
} // end loop
// the next line will cause a exception
mUsers.setText(strUsers);
mComments.setText(strComments);
} catch (Exception e) {
i++; // use this to see if it goes here in debugger
// System.out.println("exception");
// System.out.println(e.getMessage());
}
} // end methed
}
你应该考虑'AsyncTask'而不是_thread_。 –