1.介绍
2.使用方法
3.java后台代码
package com.lucky.test51url; import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView; import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; public class MainActivity extends AppCompatActivity {
Button button1;
ImageView imageView1;
Bitmap bitmap1;
String pathString="https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1552803802&di=e730996ff6ab40c6102de6cab6d6ab52&src=http://img4.duitang.com/uploads/item/201406/28/20140628082503_HcGBS.jpeg";
@SuppressLint("HandlerLeak")
Handler handler=new Handler(){ //利用hander接收线程中发送的数据,并在UI界面中显示出来
@Override
public void handleMessage(Message msg) {
if(msg.what==0x01){
imageView1.setImageBitmap(bitmap1);
}
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=findViewById(R.id.button);
imageView1=findViewById(R.id.imageView);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开辟一个新的线程
new Thread(){
@Override
public void run() {
try {
//利用URL访问网络
URL url=new URL(pathString);
URLConnection connection=url.openConnection();//获得网络连接
InputStream inputStream=connection.getInputStream();//利用connection的输入流访问网络
bitmap1=BitmapFactory.decodeStream(inputStream);
handler.sendEmptyMessage(0x01);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}); } }