java
package com.commerce.myapplication;
import androidx.annotation.NonNull;
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.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
MyHandler myHandler;
protected static final int CHANGE_UI = 1;
ImageView imageView;
class MyHandler extends Handler {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if (msg.what == CHANGE_UI) {
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.myimagetive);
myHandler = new MyHandler();
}
public void getmypic(View view) {
imageView.setBackground(getResources().getDrawable(R.drawable.ic_launcher_background));
new Thread() {
@Override
public void run() {
super.run();
try {
URL url = new URL("https://p3.ssl.qhimgs1.com/t01d2446155618ebfc9.jpg");
HttpURLConnection httpURLConnection;
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(500);
httpURLConnection.setRequestMethod("GET");
int code = httpURLConnection.getResponseCode();
if (code == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message message = new Message();
message.what = 1;
message.obj = bitmap;
myHandler.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
绿色的android



