android 线程安全Thread+handler解决联网获取数据,ui出错问题
packagedjx.android;
importdjx.downLoad.DownFiles;
importandroid.app.Activity;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.widget.Button;
importandroid.widget.TextView;
publicclassdownLoadPracticeextendsActivity{
privateButtonbutton_submit=null;
privateTextViewtextView=null;
privateStringcontent=null;
privateHandlerhandler=null;
/**Calledwhentheactivityisfirstcreated.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//创建属于主线程的handler
handler=newHandler();
button_submit=(Button)findViewById(R.id.button_submit);
textView=(TextView)findViewById(R.id.textView);
button_submit.setOnClickListener(newsubmitOnClieckListener());
}
//为按钮添加监听器
classsubmitOnClieckListenerimplementsOnClickListener{
@Override
publicvoidonClick(Viewv){
//本地机器部署为服务器,从本地下载a.txt文件内容在textView上显示
finalDownFilesdf=newDownFiles("http://192.168.75.1:8080/downLoadServer/a.txt");
textView.setText("正在加载......");
newThread(){
publicvoidrun(){
content=df.downLoadFiles();
handler.post(runnableUi);
}
}.start();
}
}
//构建Runnable对象,在runnable中更新界面
RunnablerunnableUi=newRunnable(){
@Override
publicvoidrun(){
//更新界面
textView.setText("theContentis:"+content);
}
};
}