1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| package com.example.getnet;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ImageView; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
public class MainActivity extends AppCompatActivity { ImageView imageView; Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.im1); handler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; imageView.setImageBitmap(bitmap); } };
new Thread(new Runnable() { @Override public void run() { try { URL url = new URL("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1370223763,565395419&fm=15&gp=0.jpg"); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setReadTimeout(5000); httpURLConnection.setConnectTimeout(5000); InputStream inputStream = httpURLConnection.getInputStream(); //bitmap取出对象 Bitmap bm = BitmapFactory.decodeStream(inputStream); //传入Message Message message = Message.obtain(); message.obj = bm; handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
|