Androidstudio项目连接下载网络资源

时间:2024-05-19 13:51:22

      现如今开发的Android项目基本都需要进行到网络中进行资源浏览并下载。已经很少有仅靠单机操作的手机应用APP。本次文章我们主要介绍Android项目中如何进行连接网络操作,并通过一个现实网络图片的案例进行解释。

      联网操作主要用到HttpURLConnection操作,注意事项,应为是联网耗时操作,需要开子线程。还有记得添加权限操作。

1、页面布局:(为方便起见我就只用线性布局了)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
。。。。。。。。。。。。。。。。。。。。。。。。。。。
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入网址"
        android:id="@+id/wangzhi"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="dianji"
        android:text="浏览"
        android:textSize="20sp"/>
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tuxian"/>

</LinearLayout>

为了方便起见,我button就直接设置onclick。关于button其他使用方法,可参看文章:

https://blog.****.net/qq_41562408/article/details/82899172

2、添加权限:

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

3、主页面操作:

(1)、设置变量:

private EditText wangzhi;
private ImageView tuxian;

(2)、绑定变量:

wangzhi=(EditText)findViewById(R.id.wangzhi);
tuxian=(ImageView)findViewById(R.id.tuxian);

(3)、对连接网络逻辑进行实现:(先显示代码,而后进行解释)

public void dianji(View view) {
    new Thread(){
        @Override
        public void run() {
            String path=wangzhi.getText().toString().trim();
            try {
                URL url=new URL(path);
                HttpURLConnection connection=(HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                InputStream in=connection.getInputStream();
                final Bitmap bitmap= BitmapFactory.decodeStream(in);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tuxian.setImageBitmap(bitmap);

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
}

首先因为这是联网耗时操作,所以需要开通子线程Thread();考虑到在子线程中是不能对界面UI进行操作,不过谷歌工程师考虑到这一点,设置一个api功能runOnUiThread在这上面就可以进行UI操作,当时其功能实现只是将线程之间的信息传送机制进行包装。而后文章我会对线程之间的操作进行解释。

其中HttpURLConnection操作基本成固定格式,也没多少解释的,无法就是设置请求类型、响应超时时间、获取流等,注意如果只是获取页面信息就不需要进行流的转化,因为本案例涉及到图像的显示,所以需要用到bitmap位图api功能。使用也挺方便的。里面有很多类,针对不同的类型。最终效果如图:

Androidstudio项目连接下载网络资源 Androidstudio项目连接下载网络资源功能请测有效,今天是国庆节第二天,祝各位国庆节快乐。昨天小晖也给自己好好放了个假,看了一天电视剧。。^_^。。没办法,外出名额限制,不够比基层的师兄们好多了,国庆,他们连休息的时间都没有。没办法,虽已不是军人。辛苦了!敬礼!