android 网络加载图片
通过网络链接加载网络图片
加权限,允许访问网络
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity
package com.chuanxidemo.shaoxin.demo08; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; 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 { private ImageView image; private String sIp = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1487997894044&di=569ca6601ccba29b648ce0237a81fa51&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F562c11dfa9ec8a13f075f10cf303918fa1ecc0eb.jpg"; InputStream inputStream = null; Bitmap bitmap = null; URL url = null; URLConnection connection = null; private Handler handler; //网络编程 //大作业:android studio @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); image = (ImageView) findViewById(R.id.image); Button btn = (Button)findViewById(R.id.btn); handler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); image.setImageBitmap(bitmap); } }; btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取图片 try { url = new URL(sIp); } catch (MalformedURLException e) { e.printStackTrace(); } new Thread() { @Override public void run() { super.run(); try { connection = url.openConnection(); inputStream = connection.getInputStream(); bitmap = BitmapFactory.decodeStream(inputStream); if (bitmap!=null){ handler.sendEmptyMessage(0x123); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } }); //通过http协议访问数据 //获取图片,通过网络 //客户端 //服务端 } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context="com.chuanxidemo.shaoxin.demo08.MainActivity"> <ImageView android:id="@+id/image" android:src="@mipmap/ic_launcher" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击获取图片" /> </LinearLayout>