首页 > 其他分享 >子线程网络图片查看器和Handler消息处理器

子线程网络图片查看器和Handler消息处理器

时间:2023-02-06 20:38:11浏览次数:36  
标签:layout 查看器 bitmap Handler 线程 msg import android conn


子线程网络图片查看器和Handler消息处理器_handler




子线程网络图片查看器和Handler消息处理器_xml_02


步骤: 

1.页面


3.获取http对象的连接

4.获取图片Bitmap

5.显示页面

6.权限


注意:如果在子线程中显示图片的话

CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

只有原始的线程(主线程, ui线程)才能修改view对象.

在子线程中修改view的显示状态, 会报上面异常.



子线程网络图片查看器和Handler消息处理器_Text_03



<span style="font-size:14px;"><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">

<ImageView
android:id="@+id/iv_icon"
android:layout_width="match_parent"
android:layout_height="dip"
android:layout_weight="1" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">

<EditText
android:id="@+id/et_url"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:text="http://pic55.nipic.com/file/20141208/19462408_171130083000_2.jpg"
android:layout_weight="1"
android:singleLine="true"/>

<Button
android:id="@+id/btn_subimt"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Go"
android:textSize="20sp"
/>
</LinearLayout>


</LinearLayout>
</span>



package com.sqlnetphoto;

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



import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {

private static final String TAG = "MainActivity";
private EditText etUrl;
private ImageView ivIcon;
private static final int SUCCESS = 0;
private static final int ERROR = 1;
private Handler handler = new Handler(){//import android.os.Handler;
/**
* 接收消息 主线程回调用此方法
* */
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
Log.i(TAG, "what = " +msg.what);
if(msg.what == SUCCESS){ //当前是访问网络,取显示图片
Bitmap bitmap = (Bitmap) msg.obj;
ivIcon.setImageBitmap(bitmap); //设置演示图片
}else if(msg.what == ERROR){
Toast.makeText(MainActivity.this, "抓取失败", 0).show();
}
};
};

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

ivIcon = (ImageView) findViewById(R.id.iv_icon);
etUrl = (EditText) findViewById(R.id.et_url);
findViewById(R.id.btn_subimt).setOnClickListener(this);
}

@Override
public void onClick(View v) {

final String url = etUrl.getText().toString();

new Thread(new Runnable() {

@Override
public void run() {
Bitmap bitmap = getImageFromNet(url); //防止服务器异常阻塞
//ivIcon.setImageBitmap(bitmap); //设置演示图片 这里回报异常

if(bitmap != null){
Message msg = new Message(); //消息处理对象
msg.what = SUCCESS;
msg.obj = bitmap; //把图片信息带给主线程
handler.sendMessage(msg);
}else{
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
}

}
}).start();




}

/**
* 根据url连接获取网络抓去图片返回
*
* Bitmap 相对于 图片
* */
private Bitmap getImageFromNet(String url){

HttpURLConnection conn = null;
try {
URL mURL = new URL(url); //创建一个url

//得到http的连接对象
conn = (HttpURLConnection) mURL.openConnection();

conn.setRequestMethod("GET"); //设置请求方式为get

conn.setConnectTimeout(10*1000); //设置连接服务器的超时时间,如果超出设置时间,没有连接成功,回抛异常
conn.setReadTimeout(5*1000); //设置读取数据超出时间,如果超出5s,抛异常
conn.connect();// 开始连接

int responseCode = conn.getResponseCode(); //得到服务器响应
if(responseCode == 200){ //访问成功

InputStream is = conn.getInputStream(); //获得服务器返回的流数据
Bitmap bitmap = BitmapFactory.decodeStream(is); //根据 流数据 创建一个bitmap位图对象

return bitmap;
}else {
Log.i(TAG, "访问失败: responseCode = " +responseCode);
}

} catch ( Exception e) {
e.printStackTrace();
}finally{
if(conn != null){
conn.disconnect(); //断开连接
}
}

return null;
}

}


<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sqlnetphoto"
android:versionCode="1"
android:versionName="1.0" >


<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />

<!-- inter权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
</span>







标签:layout,查看器,bitmap,Handler,线程,msg,import,android,conn
From: https://blog.51cto.com/u_15955675/6040432

相关文章

  • C++11之线程库
    在C++11之前,涉及到多线程问题,都是和平台相关的,比如Windows和Linux下各有自己的接口,这使得代码的可移植性比较差。C++11中最重要的特性就是对线程进行支持了,并且可以......
  • Android 总结4种线程中操作UI界面的方法
    我们经常会在后台线程中去做一些耗时的操作,比如去网络取数据。但是当数据取回来,需要显示到页面上的时候,会遇到一些小麻烦,因为我们都知道,android的UI页......
  • 面试八--多线程(一)线程创建的四种方法
    1进程和线程的概念进程是程序的运行实例,线程是进程中独立执行的最小单位2线程的创建、启动与应用在Java平台中创建一个线程就是创建一个Thread类的实例。线程的任务处理可......
  • Java下一代高并发技术——虚拟线程“JEP 425: Virtual Threads (Preview)”
    很多语言都有类似于“虚拟线程”的技术,比如Go、C#、Erlang、Lua等,他们称之为“协程”。不管是虚拟线程还是协程,他们都是轻量级线程,其目的都是为了提高并发能力。本节详细......
  • Python并发执行的简易实现:多进程、多线程、协程
    多进程importloggingimporttimefrommultiprocessingimportPoollogging.basicConfig(format='%(asctime)s%(message)s',level=logging.INFO)deff(x):time.sleep(......
  • Java多线程02——线程的生命周期和状态调度
    1线程的生命周期在线程的生命周期中,要经过新建​​new​​、就绪​​runnable​​、运行​​running​​、阻塞​​blocked​​和死亡​​dead​​5种状态。当线程启动后,......
  • TCP IP网络编程(14) 多线程服务端
    多线程服务器端实现  在《基于Linux的多进程服务器》中介绍了Linux下多进程服务端实现的原理,在文章《Linux下epoll》中,介绍了epoll的实现原理。多进程服务端与基于sel......
  • 多线程三大特性
     原子性:即一个操作或者多个操作 要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行。 在​​Java​​中,对基本数据类型的变量的读取和赋值操作是原子性操作,即......
  • 看一遍就懂,详解java多线程——volatile
    多线程一直以来都是面试必考点,而volatile、synchronized也是必问点,这里我试图用容易理解的方式来解释一下volatile。来看一下它的最大特点和作用:一使变量在多个线程间可见......
  • 任意组合、编排的多线程并发框架,支持任意阻塞、等待、串并行组合,回调、超时、默认值等
    并发场景可能存在的需求之——任意编排1多个执行单元的串行请求 2多个执行单元的并行请求 3阻塞等待,串行的后面跟多个并行 4阻塞等待,多个并行的执行完毕后才执行某个......