Android读取网络图片到本地的简约的实现

简介: 今天在网上看到了一个关于读取网络文件的小视频,觉得不错,拿来与大家分享思路具体的思路比较的简单,但是思想非常的单纯。那就是输入一个网址,点击按钮,将从网络上获取的一张图片显示到一个ImageView控件上。

今天在网上看到了一个关于读取网络文件的小视频,觉得不错,拿来与大家分享


思路


具体的思路比较的简单,但是思想非常的单纯。那就是输入一个网址,点击按钮,将从网络上获取的一张图片显示到一个ImageView控件上。
这样看来,我们需要用到的核心就是网络操作了。说白了,就是读取网络流文件了。

代码展示


首先是主界面的布局文件


<LinearLayout 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"
    android:orientation="vertical" >

    <EditText 
        android:id="@+id/et_website"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="please type the url "
        />
    <Button 
        android:id="@+id/btn_get"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check"

        />
    <ImageView 
        android:id="@+id/iv_picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        />

</LinearLayout>

然后是主界面的逻辑代码

package com.example.getphotobyxml;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.service.ImageService;

public class MainActivity extends Activity {

    private EditText mEt_url;
    private ImageView mIv_picture;
    private Button mBtn_get;

    /**
     * 初始化相关的需要使用到的ID
     */
    public void init() {
        mEt_url = (EditText) findViewById(R.id.et_website);
        mIv_picture = (ImageView) findViewById(R.id.iv_picture);
        mBtn_get = (Button) findViewById(R.id.btn_get);

    }

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

        //记得要调用哦
        init();

        mBtn_get.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String website = mEt_url.getText().toString();
                if (website == null || website.equals("")) {
                    Toast.makeText(MainActivity.this, "请输入正确的网址哦!",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                byte[] bytes;

                try {
                    bytes = ImageService.getImage(website);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                            bytes.length);
                    mIv_picture.setImageBitmap(bitmap);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 从网络以XML的方式获得一张图片,并显示到一个ImageView上
     * 按钮事件可以直接不注册onClickListener,而使用这个方法
     * @param view
     */
    public void getPicture(View view) {
        String website = mEt_url.getText().toString();
        if (website == null || website.equals("")) {
            Toast.makeText(this, "请输入正确的网址哦!", Toast.LENGTH_LONG).show();
            return;
        }
        byte[] bytes;

        try {
            bytes = ImageService.getImage(website);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                    bytes.length);
            mIv_picture.setImageBitmap(bitmap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

service 以及 tools助手

package com.example.service;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.example.utils.StreamTool;

/**
*图片服务的业务类
*/
public class ImageService {

    public static byte[] getImage(String website) throws Exception {

        URL url = new URL(website);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");
        if(conn.getResponseCode()==200){
            InputStream inputStream = conn.getInputStream();
            byte[] bytes = StreamTool.read(inputStream);
            return bytes;
        }
        return "读取网络数据失败".getBytes();
    }



}

package com.example.utils;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
*专门用于将输入流转换成一个字节数组的utils类
*/
public class StreamTool {

    public static byte[] read(InputStream inputStream) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = inputStream.read(buf))!=-1){
            baos.write(buf, 0 ,len);
        }
        baos.close();
        return buf;
    }

}

总结


这里面的代码是非常的简单的,我这里贴出代码的主要的目的是为了展示分层的思想,以及重构的艺术。
在代码中我们看到了,创建了专门的类来完成专门的工作。而且不同的层次的类,处理的业务也是不一样的。这样有助于我们以面向对象的方式编程,带来更加清晰的逻辑。

目录
相关文章
|
1月前
|
数据库 Android开发 开发者
构建高效Android应用:采用Kotlin协程优化网络请求处理
【2月更文挑战第30天】 在移动应用开发领域,网络请求的处理是影响用户体验的关键环节。针对Android平台,利用Kotlin协程能够极大提升异步任务处理的效率和简洁性。本文将探讨如何通过Kotlin协程优化Android应用中的网络请求处理流程,包括协程的基本概念、网络请求的异步执行以及错误处理等方面,旨在帮助开发者构建更加流畅和响应迅速的Android应用。
|
3月前
|
安全 API Android开发
Android网络和数据交互: 解释Retrofit库的作用。
Android网络和数据交互: 解释Retrofit库的作用。
38 0
|
3月前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
22 0
|
4月前
|
XML Java Android开发
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
Android App开发网络通信中使用okhttp下载和上传图片、文件讲解及实战(超详细实现用户注册信息上传 附源码)
138 0
|
7天前
|
Android开发 开发者
Android网络和数据交互: 请解释Android中的AsyncTask的作用。
Android&#39;s AsyncTask simplifies asynchronous tasks for brief background work, bridging UI and worker threads. It involves execute() for starting tasks, doInBackground() for background execution, publishProgress() for progress updates, and onPostExecute() for returning results to the main thread.
7 0
|
7天前
|
网络协议 安全 API
Android网络和数据交互: 什么是HTTP和HTTPS?在Android中如何进行网络请求?
HTTP和HTTPS是网络数据传输协议,HTTP基于TCP/IP,简单快速,HTTPS则是加密的HTTP,确保数据安全。在Android中,过去常用HttpURLConnection和HttpClient,但HttpClient自Android 6.0起被移除。现在推荐使用支持TLS、流式上传下载、超时配置等特性的HttpsURLConnection进行网络请求。
8 0
|
4月前
|
XML JSON Java
Android App开发即时通信中通过SocketIO在客户端与服务端间传输文本和图片的讲解及实战(超详细 附源码)
Android App开发即时通信中通过SocketIO在客户端与服务端间传输文本和图片的讲解及实战(超详细 附源码)
66 0
|
4月前
|
XML JSON Java
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
160 0
|
21天前
|
Android开发
Android保存图片到相册(适配android 10以下及以上)
Android保存图片到相册(适配android 10以下及以上)
20 1
|
3月前
|
JSON Java Android开发
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
Android网络和数据交互: 请解释Android中的JSON解析库,如Gson。
24 0