先上代码和结果。
代码如下:
package com.example.handlermessage;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.download.HttpDownloader;
public class MainActivity extends Activity {
//定义控件
private Button downloadBtn;
private EditText ipText;
//定义变量
private static String xml = null;
private String ipAdress;
private static Handler httpHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//findViewById
downloadBtn = (Button)this.findViewById(R.id.downloadbtn);
ipText = (EditText)this.findViewById(R.id.iptext);
//设置监听器
downloadBtn.setOnClickListener(new DownloadBtnListener());
}
@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;
}
class DownloadBtnListener implements OnClickListener{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ipAdress = ipText.getText().toString().trim();
if(ipAdress.equals("")){
Toast.makeText(MainActivity.this, "请输入正确的ip地址和端口", 1).show();
}
else{
new Thread(new HttpThread()).start();
httpHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
xml = (String)msg.obj;
System.out.println(xml);
};
};
System.out.println("-->"+xml);
}
}
}
public String downloadXML(String urlStr){
String result;
HttpDownloader hd = new HttpDownloader();
result = hd.download(urlStr);
return result;
}
class HttpThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
String xmlPath = downloadXML("http://".concat(ipAdress).concat("/mp3/resources.xml"));
Message httpMsg = httpHandler.obtainMessage();
httpMsg.obj = xmlPath;
MainActivity.httpHandler.sendMessage(httpMsg);
}
}
}
输出结果如下:
问题说明:不知为何先输出了Handler外的那个输出语句,再输出Handler里边的输出语句,而且Handler外的xml输出结果仍然为null,而Handler里边的输出结果才是我想要的结果,两个xml应该是同一个变量吧,如何才能使得xml在Handler外输出正常的结果?
新手自学,希望各位指点了!
------解决方案--------------------
那你只能取消线程,全部都是一步步执行下来了