android 学习随笔七(网络:图片及文本传输及线程关系 )

时间:2024-10-09 22:34:08
  • 主线程、子线程、UI的关系

android 学习随笔七(网络:图片及文本传输及线程关系  )

  • 简单的HTTP请求

--------------------------------------------------------

public class MainActivity extends Activity {

Handler handler = new Handler(){
//只要消息队列有消息,此方法就会在主线程执行
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
//刷新UI
//把下载的图片显示
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap)msg.obj);
break;
case 2:
Toast.makeText(MainActivity.this, "请求失败", 0).show();
break;
case 3:
Toast.makeText(MainActivity.this, "连接开始", 0).show();
break;
case 4:
Toast.makeText(MainActivity.this, "连接成功", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void click(View v){
Thread t= new Thread(){
@Override
public void run() {
//String path="http://192.168.1.106/adtest/11.jpg";
String path="http://10.0.2.2/adtest/11.jpg";
//发送HTTP请求
try {
//1.使用网址构造一个URL对象
URL url=new URL(path);
//获取连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些属性
//设置请求方式
conn.setRequestMethod("GET");
//设置请求超时
conn.setConnectTimeout(8000);
//设置读取超时
conn.setReadTimeout(8000);
handler.sendEmptyMessage(3);
//发送请求,建立连接
conn.connect();
handler.sendEmptyMessage(4);
//判断请求是否成功
if(conn.getResponseCode() == 200){
//获取服务器返回的流,流里就是客户端请求的数据
InputStream is = conn.getInputStream();
//读取流里数据,构造出一张图片
Bitmap bm = BitmapFactory.decodeStream(is);

//当子线程需要刷新UI时,只需发送一条消息至消息队列
Message msg = new Message();
//消息对象可以携带数据
msg.obj = bm;
//使用WHAT标注消息类型
msg.what = 1;
handler.sendMessage(msg);
}
else{
//如果消息不携带数据,可以用handler发空消息,不用创建Message
//如果消息池有消息,取出消息池第一条消息(复用空闲消息),返回,如果没有,就NEW一个消息返回
// Message msg = handler.obtainMessage();
// msg.what = 2;
// handler.sendMessage(msg);

handler.sendEmptyMessage(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}

------------------------------------------------------------------------------------------

  • 添加缓存机制

public class MainActivity extends Activity {

Handler handler = new Handler(){
//只要消息队列有消息,此方法就会在主线程执行
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
//刷新UI
//把下载的图片显示
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap((Bitmap)msg.obj);
break;
case 2:
Toast.makeText(MainActivity.this, "请求失败", 0).show();
break;
case 3:
Toast.makeText(MainActivity.this, "连接开始", 0).show();
break;
case 4:
Toast.makeText(MainActivity.this, "连接成功", 0).show();
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void click(View v){
Thread t= new Thread(){
@Override
public void run() {
//String path="http://192.168.1.106/adtest/11.jpg";
//String path="http://10.0.2.2/adtest/11.jpg";
final String path="http://10.0.2.2";
final File file = new File(getCacheDir() + getFileNameFromPath(path));
if(file.exists()){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
//当子线程需要刷新UI时,只需发送一条消息至消息队列
Message msg = new Message();
//消息对象可以携带数据
msg.obj = bm;
//使用WHAT标注消息类型
msg.what = 1;
handler.sendMessage(msg);

//在主线程可以直接显示
// ImageView iv = (ImageView) findViewById(R.id.iv);
// iv.setImageBitmap((Bitmap)msg.obj);
}
else
{
//发送HTTP请求
try {
//1.使用网址构造一个URL对象
URL url=new URL(path);
//获取连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些属性
//设置请求方式
conn.setRequestMethod("GET");
//设置请求超时
conn.setConnectTimeout(8000);
//设置读取超时
conn.setReadTimeout(8000);
handler.sendEmptyMessage(3);
//发送请求,建立连接
//conn.connect();

//判断请求是否成功(请求时建立连接)
if(conn.getResponseCode() == 200){
handler.sendEmptyMessage(4);
//获取服务器返回的流,流里就是客户端请求的数据
InputStream is = conn.getInputStream();

//读取数据(1K),缓存数据
byte[] b = new byte[1024];
int len;

FileOutputStream fos = new FileOutputStream(file);
while((len = is.read(b)) != -1){
fos.write(b, 0, len);
}
fos.close();
//读取流里数据,构造出一张图片,缓存把流里的数据读完,流里已经没有数据了
//Bitmap bm = BitmapFactory.decodeStream(is);

Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
//当子线程需要刷新UI时,只需发送一条消息至消息队列
Message msg = new Message();
//消息对象可以携带数据
msg.obj = bm;
//使用WHAT标注消息类型
msg.what = 1;
handler.sendMessage(msg);
}
else{
//如果消息不携带数据,可以用handler发空消息,不用创建Message
//如果消息池有消息,取出消息池第一条消息(复用空闲消息),返回,如果没有,就NEW一个消息返回
// Message msg = handler.obtainMessage();
// msg.what = 2;
// handler.sendMessage(msg);

handler.sendEmptyMessage(2);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
};
t.start();
}

public String getFileNameFromPath(String path) {
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
}

------------------------------------------------------------------------------------------------------------

  •  引用现成代码

https://github.com/loopj/android-smart-image-view

下载解压拷贝到工程中来

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ecollab.smartimageview.MainActivity" >

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查看网络图片"
android:onClick="click"
/>

<com.loopj.android.image.SmartImageView
android:id="@+id/siv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>

</RelativeLayout>

-------------------------------------------------------------------------------

public void click(View v)
{
SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
//请求网络图片
siv.setImageUrl("http://10.0.2.2:80/adtest/11.jpg");
}

 

  •  文本查看器

------------------------------------------------------------------------------------------------

public class Tools {
public static String getTextFromStream(InputStream is)
{
byte[] b = new byte[1024];
int len;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while((len = is.read(b)) != -1){
bos.write(b, 0, len);
}
//把字节数组输出流转换成字节数组,然后用字节数组构造一个字符串
String text = new String(bos.toByteArray());
//String text = new String(bos.toByteArray(),"gbk");
return text;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

--------------------------------------------------------------------------------------------

public class MainActivity extends Activity {
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
TextView tv = (TextView) findViewById(R.id.tv);
tv.setText((String)msg.obj);
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void click(View v)
{
final String path = "http://10.0.2.2:80/adtest/baidu.html";
Thread t = new Thread(){
@Override
public void run() {
URL url;
try {
//使用网址构造URL
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
if(conn.getResponseCode() == 200){
InputStream is = conn.getInputStream();
String text = Tools.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}