1. 原理图

2. 示例代码 (网络图片查看器)

(1)  HttpURLConnection

(2) SmartImageView (开源框架:https://github.com/loopj/android-smart-image-view

Handler 类, 消息队列处理

访问互联网需要权限

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

布局

<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"
tools:context=".MainActivity" > <ImageView android:id="@+id/iv_image"
android:layout_weight="100"
android:layout_width="match_parent"
android:layout_height="0dp" /> <EditText android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/link"
android:hint="输入网络链接" /> <Button android:id="@+id/bt_link"
android:onClick="click"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查看" /> </LinearLayout>

MainActivity.java

package com.kevin.netimageview;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; import javax.net.ssl.HttpsURLConnection; import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast; public class MainActivity extends Activity { protected static final int CHANGE_UI = 0;
protected static final int ERROR = 1;
protected static final int LINK = 2;
private EditText et_path;
private ImageView iv_image; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = (EditText) findViewById(R.id.et_path);
iv_image = (ImageView) findViewById(R.id.iv_image);
} private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg){ //消息处理
if(msg.what==CHANGE_UI){
Toast.makeText(getApplicationContext(), "CHANGE_UI", Toast.LENGTH_SHORT).show();
Bitmap bitmap = (Bitmap) msg.obj;
iv_image.setImageBitmap(bitmap);
}else if(msg.what==ERROR){
Toast.makeText(getApplicationContext(), "发生ERROR", Toast.LENGTH_SHORT).show();
}
else if(msg.what==LINK){
Toast.makeText(getApplicationContext(), "将要获取响应", Toast.LENGTH_SHORT).show();
}
}
}; public void click(View v){
new Thread(){
public void run(){ String path = et_path.getText().toString().trim();
if(path==null || path.length()==0){
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
return;
} System.out.println("xxxxx");
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置请求方式 为 GET
conn.setRequestMethod("GET");
// 设置请求超时时间
conn.setConnectTimeout(5000);
// 注意: 下面的读取超时的时间.
// conn.setReadTimeout(timeoutMillis);
conn.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)");
Message msg = new Message();
msg.what = LINK;
handler.sendMessage(msg);
// 把get请求发送出去,获取服务器上的数据
// 获取服务器的返回码 状态码
int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
Bitmap bitMap = BitmapFactory.decodeStream(is);
msg = new Message();
msg.what = CHANGE_UI;
msg.obj = bitMap;
handler.sendMessage(msg); //发送消息
} } catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg); //发送消息
}
}
}.start();
}
}

可输入的参考URL: http://d.hiphotos.baidu.com/image/w%3D310/sign=07ccb79279cb0a4685228d385b62f63e/902397dda144ad3452bdd2efd2a20cf431ad8553.jpg

(2)SmartImageView 使用开源框架

main.xml 布局文件ImageView 改成 SmartImageView即可, 需要引用类的全路径

<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"
tools:context=".MainActivity" > <com.loopj.android.image.SmartImageView android:id="@+id/siv_image"
android:layout_weight="100"
android:layout_width="match_parent"
android:layout_height="0dp" /> <EditText android:id="@+id/set_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/link"
android:hint="输入网络链接" /> <Button android:id="@+id/sbt_link"
android:onClick="click2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查看" /> </LinearLayout>

MainActivity.java中直接操作 SmartImageView即可,

public void click2(View v){
SmartImageView iv_image = (SmartImageView) findViewById(R.id.siv_image);
String url = et_path.getText().toString().trim();
//可以加入两张图片,分别在loading和获取文件失败的时候显示出来
iv_image.setImageUrl(url, R.drawable.ic_launcher, R.drawable.ic_launcher);
Toast.makeText(this, "显示网络图片", Toast.LENGTH_SHORT).show();
}

3. 示例代码 (网络html查看器)

原理和2的代码相似, 不过要注意乱码问题的处理

MainActivity.java

public class MainActivity extends Activity {
protected static final int PATH_CANOT_NULL = 1;
protected static final int GET_HTML_ERROR = 2;
protected static final int SET_TEXT = 3;
private TextView tv_content;
private EditText et_path; //在主线程创建一个消息处理器
private Handler handler = new Handler(){
//当解析到新的消息时候的处理方法
@Override
public void handleMessage(Message msg) {
//当有新的消息到来时候的处理方法
switch (msg.what) {
case PATH_CANOT_NULL:
Toast.makeText(getApplicationContext(), "路径不能为空", 1).show();
break;
case GET_HTML_ERROR:
Toast.makeText(getApplicationContext(), "获取html失败", 1).show();
break;
case SET_TEXT:
String text = (String) msg.obj;//重新获取到消息对象里面的文本
tv_content.setText(text);
break;
}
super.handleMessage(msg);
} }; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); tv_content = (TextView) findViewById(R.id.tv_content);
et_path = (EditText) findViewById(R.id.et_path);
} public void viewHtml(View view) {
//子线程
new Thread() {
public void run() {
String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
//Toast.makeText(MainActivity.this, "路径不能为空", 1).show();
System.out.println("路径不能为空");
Message msg = new Message();
msg.what = PATH_CANOT_NULL; //指定消息的类型 一般用一个int类型的数据 区分不同的消息
handler.sendMessage(msg);
return;
}
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
Thread.sleep(5000);// 模拟一个网络访问的延迟
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
String text = StreamTools.readFromStream(is);
//tv_content.setText(text);
Message msg = new Message();
msg.what = SET_TEXT; //指定消息的类型 一般用一个int类型的数据 区分不同的消息
msg.obj = text;//把要传递的数据 放在这个消息里面
handler.sendMessage(msg); } else {
//Toast.makeText(MainActivity.this, "获取html失败", 0).show();
System.out.println("获取html失败");
Message msg = new Message();
msg.what = GET_HTML_ERROR; //指定消息的类型 一般用一个int类型的数据 区分不同的消息
handler.sendMessage(msg);
} } catch (Exception e) {
e.printStackTrace();
//Toast.makeText(MainActivity.this, "获取html失败", 0).show();
System.out.println("获取html失败");
Message msg = new Message();
msg.what = GET_HTML_ERROR; //指定消息的类型 一般用一个int类型的数据 区分不同的消息
handler.sendMessage(msg);
} };
}.start();
}
}

StreamTools.java 工具类, 将InputStream转换为String

public class StreamTools {
/**
* 工具方法 把流里面的内容 转化成 String 字符串
* @param is 输入流
* @return String 字符串
* @throws IOException
*/
public static String readFromStream(InputStream is) throws Exception{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
baos.write(buffer, 0, len);
}
is.close();
String result = baos.toString();
if(result.contains("gb2312")){
// result.getbytes("utf-8")
byte[] temp = baos.toByteArray();
result = new String(temp, "gb2312");
}
baos.close();
return result;
}
}

Android -- 网络图片查看器,网络html查看器, 消息机制, 消息队列,线程间通讯的更多相关文章

  1. android线程间通讯

    近来找了一些关于android线程间通信的资料,整理学习了一下,并制作了一个简单的例子. andriod提供了 Handler 和 Looper 来满足线程间的通信.例如一个子线程从网络上下载了一副图 ...

  2. Android 异步任务,通过PHP访问数据库,多线程,线程间通讯

    文章列表MainActivity.java package com.eric.asynctask; import java.io.IOException; import java.util.Array ...

  3. Android线程间通讯的几种方式

    1.runOnUiThread(Runnable)              在子线程中直接使用该方法,可以更新UI runOnUiThread(new Runnable(){//更新UI       ...

  4. Android消息传递之Handler消息机制

    前言: 无论是现在所做的项目还是以前的项目中,都会遇见线程之间通信.组件之间通信,目前统一采用EventBus来做处理,在总结学习EventBus之前,觉得还是需要学习总结一下最初的实现方式,也算是不 ...

  5. 深入理解 Android 消息机制原理

    欢迎大家前往腾讯云社区,获取更多腾讯海量技术实践干货哦~ 作者:汪毅雄 导语: 本文讲述的是Android的消息机制原理,从Java到Native代码进行了梳理,并结合其中使用到的Epoll模型予以介 ...

  6. 无废话Android之内容观察者ContentObserver、获取和保存系统的联系人信息、网络图片查看器、网络html查看器、使用异步框架Android-Async-Http(4)

    1.内容观察者ContentObserver 如果ContentProvider的访问者需要知道ContentProvider中的数据发生了变化,可以在ContentProvider 发生数据变化时调 ...

  7. Android 网络HTML查看器

    本文实现一个基于Android的网络HTML查看器 新建项目,项目布局文件如下: <LinearLayout xmlns:android="http://schemas.android ...

  8. Android仿微信朋友圈图片查看器

    转载请注明出处:http://blog.csdn.net/allen315410/article/details/40264551 看博文之前,希望大家先打开自己的微信点到朋友圈中去,细致观察是不是发 ...

  9. [原创]java WEB学习笔记66:Struts2 学习之路--Struts的CRUD操作( 查看 / 删除/ 添加) 使用 paramsPrepareParamsStack 重构代码 ,PrepareInterceptor拦截器,paramsPrepareParamsStack 拦截器栈

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

随机推荐

  1. TypeError: cannot use a string pattern on a bytes-like object的解决办法

    #!/usr/python3 import re import urllib.request def gethtml(url): page=urllib.request.urlopen(url) ht ...

  2. httprunner上传文件multipart/form-data

    Content-Type = multipart/form-data#上传文件 Rquest Payload ------WebKitFormBoundarymAyGmnyhpf3UBdec    C ...

  3. python学习笔记(十九)发送邮件

    在python开发项目或者做自动化测试时候,在测试完成后需要将测试结果总结后进行上报,那么我们就可以通过发送邮件来完成这项工作. 下面我们来看看python中怎么发送邮件的,python中发送邮件可以 ...

  4. libxml2 在mingw中 xmlfree连接错误问题

    libxml2 在mingw中 xmlfree连接错误问题 2013年10月02日 ⁄ 综合 ⁄ 共 1527字 ⁄ 字号 小 中 大 ⁄ 评论关闭 原地址:http://blog.csdn.net/ ...

  5. The Cheap KD 10 is my best shoe yet

    10 years of anything is fairly huge Cheap KD 10, but adding something as great as Flyknit causes it ...

  6. SQL Server 使用 Hierarchyid 操作层次结构数据

    层次结构数据定义为一组通过层次结构关系互相关联的数据项. 在层次结构关系中,一个数据项是另一个项的父级或子级. sql server2008开始内置的 hierarchyid 数据类型使存储和查询层次 ...

  7. DevStore分享:详析消费者十大心理学

    做生意,其实就是一个恋爱的过程,让用户找到你.了解你,爱上你.而这个过程中的关键点就是用户.只要与用户心理相关的,那么就会影响到他们的购买决策.而作为卖方的你,就应该了解消费者心里面在想些什么. 第一 ...

  8. 2017 Multi-University Training Contest - Team 3 hdu6060 RXD and dividing

    地址:http://acm.split.hdu.edu.cn/showproblem.php?pid=6060 题目: RXD and dividing Time Limit: 6000/3000 M ...

  9. 【android】开发笔记---存储篇

    SQLite批量插入数据 当我们执行 db.execSQL("sql语句")的时候,系统进行了一次IO操作,当批量插入成千上万条时,就会消耗掉许多资源. 解决之道是通过事务,统一提 ...

  10. Oracle中的substr()函数详解案例

    1)substr函数格式   (俗称:字符截取函数) 格式1: substr(string string, int a, int b); 格式2:substr(string string, int a ...