Android中如何使用网络

Android中网络完全使用JavaSE的网络API,这样很多以前的网络代码也完全可以移植到Android平台。Android中使用网络需要添加网络权限android.permission.INTERNET。网络操作是耗时操作,安卓要求网络操作不能和主线程放在一起,而子线程不能更新UI,因此通常需要使用google封装好的消息队列进行线程通信。

MainActivity.java

public class MainActivity extends Activity
{
    public ImageView imageView;
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            imageView.setImageBitmap((Bitmap) msg.obj);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.imageView = (ImageView) findViewById(R.id.image_view);
    }

    public void getImageFromInternet()
    {
        new Thread(new Runnable() {
            @Override
            public void run()
            {
                try
                {
                    URL url = new URL("http://192.168.1.104/icons/ubuntu-logo.png");
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setConnectTimeout(10000);
                    httpURLConnection.connect();

                    int code = httpURLConnection.getResponseCode();
                    if(code == 200)
                    {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        Message message = new Message();
                        message.obj = bitmap;
                        handler.sendMessage(message);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    public void click(View view)
    {
        getImageFromInternet();
    }
}

上述代码十分简单,子线程请求一个网络图片并送入消息队列,主线程消息队列轮询得到这个图片并显示到ImageView中。

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。