应用在网络连接上,onrestart后不会重新联网获取图片,省去了流量,
public class MainActivity extends AppCompatActivity { ImageView imageView; private LruCache<String, Bitmap> lruCache; Bitmap bitmap; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.image); long maxMemory = Runtime.getRuntime().maxMemory(); int cacheSize = (int) (maxMemory / 8); lruCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; } class BitmapThread extends Thread { private String bitmapUrl; BitmapThread(String bitmapUrl) { this.bitmapUrl = bitmapUrl; } @Override public void run() { Log.i("名字", "run: " + Thread.currentThread().getName()); Bitmap bitmap3 = null; HttpURLConnection connection = null; InputStream inputStream = null; try { URL url = new URL(bitmapUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { inputStream = connection.getInputStream(); bitmap3 = BitmapFactory.decodeStream(inputStream); } handler.obtainMessage(1, bitmap3).sendToTarget(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { Log.i("线程名字", "hanlder handleMessage: " + Thread.currentThread().getName()); switch (msg.what) { case 1: bitmap = (Bitmap) msg.obj; imageView.setImageBitmap(bitmap); lruCache.put("a", bitmap); break; } } }; @Override protected void onStart() { super.onStart(); Bitmap bitmap2 = lruCache.get("a"); if (bitmap2 == null) { new BitmapThread("https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=3453332705,4236610029&fm=26&gp=0.jpg").start(); } else { imageView.setImageBitmap(bitmap2); } } }
原文地址:https://www.cnblogs.com/Ocean123123/p/10981355.html
时间: 2024-10-13 15:03:12