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
}
}