如何用HttpUrlConnection加载图片
代码展示
xml代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.zhang.myapplicationaas.Main3Activity">
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="60dp" />
<ImageView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
java代码
public class Main3Activity extends AppCompatActivity {
private Button bt;
private ImageView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
bt=findViewById(R.id.bt);
tv=findViewById(R.id.tv);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new as().execute(1);
}
});
}
class as extends AsyncTask<Integer,Integer,Integer>{
Bitmap f;//位图文件
@Override
protected Integer doInBackground(Integer... integers) {
try {
URL url=new URL("http://img31.mtime.cn/mg/2012/10/30/201631.37192876.jpg");
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
InputStream i=connection.getInputStream();
f= BitmapFactory.decodeStream(i);//类,通过各种解码获取位图图像;解析出原始图,不会进行屏幕适配
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer==1){
tv.setImageBitmap(f);
}
}
}
}