package com.example.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
protected static final int SHOW_REPONSE = 0;
private Button sendButton;
private TextView responseText;
//private static Handler handler;
private final Handler handler = new Handler(){
public void hadleMessage(Message msg){
switch (msg.what) {
case SHOW_REPONSE:
String response = (String) msg.obj;
//在这里进行UI操作
responseText.setText(response);
Log.d("MainActivity", "2");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
// 初始化界面
sendButton = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.request_text);
sendButton.setOnClickListener(this);
Log.d("MainActivity", "3");
}
@Override
public void onClick(View v) {
// 发送请求按钮点击相应事件
if(v.getId() == R.id.send_request){
sendRequestWithHttpURLConnection();
Log.d("MainActivity", "4");
}
}
private void sendRequestWithHttpURLConnection() {
// 开启线程发起请求
new Thread(new Runnable() {
@Override
public void run() {
Log.d("MainActivity", "5");
// TODO Auto-generated method stub
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
Log.d("MainActivity", "6");
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
Log.d("MainActivity", "7");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
Log.d("MainActivity", "8");
StringBuilder response = new StringBuilder();
Log.d("MainActivity", "9");
String line;
Log.d("MainActivity", "1");
while((line = reader.readLine()) != null){
response.append(line);
}
Message message = new Message();
Log.d("MainActivity", "10");
message.what = SHOW_REPONSE;
//服务器返回的结果存放在Message中
message.obj = response.toString();
Log.d("MainActivity", "11");
handler.sendMessage(message);
Log.d("MainActivity", "12");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(connection != null){
connection.disconnect();
}
}
}
}).start();
}
}
【Handler问题求指导】使用Handler遇到了问题
最新推荐文章于 2023-08-14 12:16:17 发布