重点分析:
1、安卓4.0以上不支持使用主线程进行耗时的操作,例如网络请求等
2、子线程不允许更改UI界面,需要利用消息机制
一、创建UI界面:
如图:
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入图片地址"
android:text="https://www.baidu.com/img/bd_logo1.png"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="加载图片"
android:id="@+id/bt1"
android:onClick="pic_download"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv1"/>
</LinearLayout>
二、在MainActivity中创建点击事件并绑
package com.example.administrator.demo_picdownload;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText et1;
private ImageView iv1;
private static String TAG="TEST";
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
Bitmap bitmap=(Bitmap) msg.obj;
iv1.setImageBitmap(bitmap);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=findViewById(R.id.et1);
iv1=findViewById(R.id.iv1);
}
public void pic_download(View view){
final String path=et1.getText().toString().trim();
new Thread(){
public void run(){
try {
Log.i(TAG,"START");
URL url=new URL(path);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(3000);
String type=conn.getContentType();
int len=conn.getContentLength();
int code=conn.getResponseCode();
Log.i(TAG,"状态码:"+code+"图片大小:"+len+"文件类型:"+type);
if (code==200){
InputStream is=conn.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(is);
Message msg=Message.obtain();
msg.obj=bitmap;
// msg.what=1;
handler.sendMessage(msg);
is.close();
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG,"GG");
}
}
}.start();
}
}