XML中的代码:
<Button
android:id="@+id/button"
android:text="获取图片"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ImageView
android:id="@+id/image"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_below="@id/button"
/>
Activity中的代码:
private String lujing="http://img.netbian.com/file/2017/0216/39f11cd4d8270ec2c534dff72c9c6a83.jpg";
private final int UPDATE_UI=1;
private ImageView image;
private Button button;
@SuppressLint("HandlerLeak")
private Handler hander=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UPDATE_UI:
image.setImageBitmap((Bitmap) msg.obj);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = findViewById(R.id.image);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(
new Runnable() {
@Override
public void run() {
huoqu();
}
}
).start();
}
});
}
private void huoqu(){
try {
URL url=new URL(lujing);
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//P判断网络类型
int shijian;
if (wangluo()){
shijian=10000;
}else{
shijian=5000;
}
urlConnection.setReadTimeout(shijian);
urlConnection.setConnectTimeout(shijian);
int responseCode = urlConnection.getResponseCode();
if (responseCode==200){
Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
hander.sendMessage(hander.obtainMessage(UPDATE_UI,bitmap));
}
} catch (Exception e) {
e.printStackTrace();
}
}
//判断是否是手机网络
private boolean wangluo(){
ConnectivityManager cm= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
return activeNetworkInfo.getType()==ConnectivityManager.TYPE_MOBILE;
}