发布于 2016-08-21 03:34:23 | 121 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要为大家详细介绍了如何简单实现Android读取网络图片到本地的方法,感兴趣的小伙伴们可以参考一下

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

思路

具体的思路比较的简单,但是思想非常的单纯。那就是输入一个网址,点击按钮,将从网络上获取的一张图片显示到一个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;
  }

}

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



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务