网络多线程
AndroidManifest.xml
activity_main.xml
MainActivity.java
package com.example.nethanderdemo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public Handler mHander = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 0x111){
TextView textView = findViewById(R.id.tv1);
textView.setText((String) msg.obj);
}
}
};
public void btnClick1(View view) {
// 使用网络API 访问百度,将返回的源代码输出到TextView中
// 一些常见问题
// 0. 网络操作需要网络权限
// 1. android中的网络操作属于耗时操作,耗时操作不允许在主线程执行
// 2. 界面操作只能在主线程操作
Runnable runnable = new Runnable() {
@Override
public void run() {
String path = "http://www.baidu.com";
try {
// 1. 创建URL对象,连接对象,设置信息
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
// 2. 发出请求,获取响应结果
int code = connection.getResponseCode();
if(code == 200){
// 读取数据,保存数据
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte bytes[] = new byte[1024];
int retCount = -1;
while(true){
retCount = inputStream.read(bytes,0,1024);
if(retCount == -1) break;
outputStream.write(bytes,0,retCount);
}
String string = new String(outputStream.toString());
Log.d("15pb",string);
// TextView textView = findViewById(R.id.tv1);
// textView.setText(string);
// 1. 创建消息对象
Message message = new Message();
message.obj = string;
message.what = 0x111;
// 2. 使用handler发送消息到主线程中
mHander.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
Thread thread1 = new Thread(runnable);
thread1.start();
}
public void btnClick0(View view) {
// 使用Thread,创建对象指定回调,启动线程
Thread thread = new Thread(){
@Override
public void run() {
super.run();
Log.d("15pb","thread");
}
};
thread.start();
//使用Runnable创建回调对象,使用Thread启动
Runnable runnable = new Runnable() {
@Override
public void run() {
Log.d("15pb","runnable");
}
};
Thread thread1 = new Thread(runnable);
thread1.start();
}
}