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. 机房断电导致MySQL同步1594错误

    1.错误信息 Last_IO_Error: Got fatal error from master when reading data from binary log: ' at 208645951. ...

  2. python学习笔记(二十一)构造函数和析构函数

    python中的特殊方法,其中两个,构造函数和析构函数的作用: 比说“__init__”这个构造函数,具有初始化的作用,也就是当该类被实例化的时候就会执行该函数.那么我们就可以把要先初始化的属性放到这 ...

  3. Oracle 性能调优 SQL_TRACE

    思维导图 Oracle优化10-SQL_TRACE解读 Oracle优化11-10046事件 概述 当我们想了解一条SQL或者是PL/SQL包的运行情况时,特别是当他们的性能非常差时,比如有的时候看起 ...

  4. EventFiringWebDriver网页事件监听(一)

    Selenium提供了很多的event listening functions来跟踪脚本执行过程中的events. How it works? 在注册了listener的webDriver里面,这些l ...

  5. flask扩展 -- flask-script

    Flask-Scropt插件:为在Flask里编写额外的脚本提供了支持.这包括运行一个开发服务器,一个定制的Python命令行,用于执行初始化数据库.定时任务和其他属于web应用之外的命令行任务的脚本 ...

  6. php处理restful请求的路由(转载 http://www.jb51.net/article/47333.htm)

    <?php    class Router {        // 路由表        private $routers = array(            array("nam ...

  7. Laravel 文档中的 Service Providers

    $this->app->singleton('ReportServices', function () { return new \App\Services\ReportServices( ...

  8. 移动端web开发 尽量哪些标签 常用标签及注意事项

    H5手机移动端WEB开发资源整合 常用的标签及注意事项: https://blog.csdn.net/u012118993/article/details/56023399 移动前端不得不了解的htm ...

  9. 最值得阅读学习的 10 个 C 语言开源项目代码

    1. Webbench Webbench是一个在linux下使用的非常简单的网站压测工具.它使用fork()模拟多个客户端同时访问我们设定的URL,测试网站在压力下工作的性能,最多可以模拟3万个并发连 ...

  10. 如何高效的遍历HashMap 以及对key 进行排序

    Map<Integer ,Object> map = new HashMap<Integer,Object>(); for(int i = 0; i<=100;i++){ ...