您的位置:首页 > 理论基础 > 计算机网络

android下简单的网络图片查看器

2014-03-01 14:37 567 查看
activity_main.xml

<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" >

<EditText
android:id="@+id/et_path"
android:text="http://192.168.1.134:8080/tomcat.gif"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入图片路径" />

<ImageView
android:id="@+id/iv_image"
android:layout_weight="1000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />

<Button
android:onClick="click"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="查看" />

</LinearLayout>

MainActivity.java
package com.itheima.netimageviewer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Log;
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 SET_IMAGE = 1;
protected static final int LOAD_IMAGE_ERROR = 2;
protected static final int NETWORK_ERROR = 3;
private static final String TAG = "MainActivity";
private EditText et_path;
private ImageView iv_image;

// 1.创建一个消息的处理器.
private Handler handler = new Handler() { // 主线程执行.
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SET_IMAGE:
Bitmap bitmap = (Bitmap) msg.obj;
iv_image.setImageBitmap(bitmap);
break;
case LOAD_IMAGE_ERROR:
Toast.makeText(MainActivity.this, "获取图片失败", 1).show();
break;
case NETWORK_ERROR:
Toast.makeText(MainActivity.this, "网络异常", 1).show();
break;
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("name:" + Thread.currentThread().getName());
et_path = (EditText) findViewById(R.id.et_path);
iv_image = (ImageView) findViewById(R.id.iv_image);
}

public void click(View view) {
final String path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "图片路径不能为空", 1).show();
return;
}
if (path.startsWith("http://")) {
// 判断图片是否有缓存文件.
File file = new File(getCacheDir(), getFileName(path));
if (file.exists() && file.length() > 0) {
// 加载缓存
iv_image.setImageURI(Uri.fromFile(file));
Log.i(TAG,"加载缓存图片");
} else {
Log.i(TAG,"开启线程下载图片");
new Thread() {
public void run() {
// 从服务器获取这个图片 显示出来.
// http get请求
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// get 设置请求方式 post
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);

int code = conn.getResponseCode();
if (code == 200) {
// 请求成功
InputStream is = conn.getInputStream();// 获取服务器端返回的数据.
File file = new File(getCacheDir(),
getFileName(path));
FileOutputStream fos = new FileOutputStream(
file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
Bitmap bitmap = BitmapFactory.decodeFile(file
.getAbsolutePath());
// iv_image.setImageBitmap(bitmap);
Message msg = new Message();
msg.what = SET_IMAGE;
msg.obj = bitmap;
handler.sendMessage(msg);// 在子线程 发送消息 给主线程
// 消息里面存放的有获取到的图片.
} else {
// Toast.makeText(MainActivity.this, "获取图片错误",
// 1).show();
Message msg = new Message();
msg.what = LOAD_IMAGE_ERROR;
handler.sendMessage(msg);

}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// Toast.makeText(MainActivity.this, "网络异常",
// 1).show();
Message msg = new Message();
msg.what = NETWORK_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
};
}.start();
}
} else {
Toast.makeText(this, "路径错误", 1).show();
return;
}

}

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

}


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.netimageviewer"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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="com.itheima.netimageviewer.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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络图片查看器