且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android 网络编程--URL互联网资源

更新时间:2021-08-18 11:19:18

1.加入权限

 <uses-permission android:name="android.permission.INTERNET"/>

2.Layout设计

1
2
3
4
5
6
7
8
9
10
11
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
 
</RelativeLayout>

 3.Code设计

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
public class MainActivity extends Activity {
 
    private Bitmap bitmap;
    private ImageView show;
 
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                show.setImageBitmap(bitmap);
            }
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = (ImageView) this.findViewById(R.id.imageView);
 
        new Thread() {
              
            @Override 
            public void run() {
                super.run(); 
                try {
                    URL url = new URL(
                            "http://a.hiphotos.baidu.com/image/h%3D220/sign=bd9eb2ea07087bf462ec50ebc2d2575e/d439b6003af33a87495b8dbbc35c10385343b559.jpg");
                    InputStream inputStream = url.openStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                    handler.sendEmptyMessage(1);
                    inputStream.close();
 
                catch (Exception e) {
                    e.printStackTrace();
                }
 
            };
 
        }.start();
    }
 
}

 



本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/p/5124975.html,如需转载请自行联系原作者