MainActivity的代码:
package com.example.androidsendnum;
import java.io.InterruptedIOException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int i;
int j;
boolean flag;
Thread thread = new Thread();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button bnSend =(Button)findViewById(R.id.send);
final Button bnStop =(Button)findViewById(R.id.stop);
TextView sendView =(TextView)findViewById(R.id.sendtext);
TextView receiveView =(TextView)findViewById(R.id.receivetext);
bnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag=true;
thread.start();
}
});
bnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag=false;
}
});
sendView.setText(i);
receiveView.setText(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void run() {
// TODO Auto-generated method stub
while(flag){
for(i=1,j=0;j<100;i++,j++){
try {
thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
但是在模拟器中就打不开
你想通过thread循环给textview赋值?
Android不允许在非主线程中操作UI。
所以你需要用到handler 处理、
MyHandler handler = new MyHandler();
handler.sendEmptyMessage(msg);
..
..
..
private Class MyHandler extends Handler{
@Override
handlerMessage(Message msg){
//此处处理你发送的handler,然后控制UI
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。