下载 网络图片

AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xiesir.example21downimage"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
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: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.xiesir.example21downimage.MainActivity"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btnDown" android:text="查看" android:onClick="downClick" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/etURL" android:hint="请输入网址" android:lines="1" android:layout_toLeftOf="@id/btnDown" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout> <ImageView android:id="@+id/iv" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java:
package com.xiesir.example21downimage; 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.EditText; import android.widget.ImageView; import android.widget.Toast; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { Handler handler = new Handler() { // 只要消息队列有消息,此方法就会在主线程执行 public void handleMessage(Message msg) { // 刷新UI switch (msg.what) { case 1: ImageView iv = (ImageView) findViewById(R.id.iv); iv.setImageBitmap((Bitmap) msg.obj); break; case 2: Toast.makeText(MainActivity.this, "请求失败o(╯□╰)o", Toast.LENGTH_LONG).show(); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void downClick(View v) { EditText etURL = (EditText) findViewById(R.id.etURL); final String path; if (etURL.getText().toString().isEmpty()) // http://pic.pp3.cn/uploads//201509/2015092411.jpg path = "http://pic.pp3.cn/uploads//201509/2015092405.jpg"; else path = etURL.getText().toString(); final File file = new File(getCacheDir(), path.substring(path.lastIndexOf("/") + 1)); if (file.exists()) { System.out.println("从缓存获取"); Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath()); Message msg = new Message(); msg.obj = bm; msg.what = 1; handler.sendMessage(msg); // 现在在主线程中,所以也可以直接在界面上显示图像 // ImageView iv = (ImageView) findViewById(R.id.iv); // iv.setImageBitmap((Bitmap) msg.obj); } else { Thread t = new Thread() { @Override public void run() { System.out.println("从网络获取"); URL url; try { // 1.使用网址构造一个URL对象 url = new URL(path); // 2.获取连接对象 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 3.设置一些属性 // 设置请求方式,注意大写 conn.setRequestMethod("GET"); // 设置请求超时 conn.setConnectTimeout(8000); // 设置读取超时 conn.setReadTimeout(8000); // 4.发送请求,建立连接,获取响应码,判断请求是否成功 if (conn.getResponseCode() == 200) { // 获取服务器返回的流,流里包含客户端请求的数据 InputStream is = conn.getInputStream(); // 我们自己读取流里的数据,读取1k,就把1k写到本地文件缓存起来 byte[] b = new byte[1024]; int len; FileOutputStream fos = new FileOutputStream(file); while ((len = is.read(b)) != -1) fos.write(b, 0, len); fos.close(); // 因为缓存时已经把流里数据读取完了,此时流里没有任何数据 // Bitmap bm = BitmapFactory.decodeStream(is); Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath()); // 当子线程需要刷新ui时,只需发送一条消息至消息队列 // 发送消息至消息队列,主线程会执行handleMessage Message msg = new Message(); //消息对象本身是可以携带数据的 msg.obj = bm; //使用what标注消息是什么类型的 msg.what = 1; handler.sendMessage(msg); } else { // 如果消息池有消息,取出消息池第一条消息,返回,如果没有,就new一个消息返回 // Message msg = handler.obtainMessage(); // msg.what = 2; // handler.sendMessage(msg); handler.sendEmptyMessage(2); } } catch (Exception e) { e.printStackTrace(); } } }; t.start(); } } }
参考:
浙公网安备 33010602011771号