一.web网络图片查看器Android
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:scaleType="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@mipmap/ic_launcher" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="56dp"
android:onClick="pre"
android:text="上一张"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="56dp"
android:onClick="next"
android:text="下一张"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity
package com.glsite.netimageviewer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int LOAD_ERROR = 2;
private static final int LOAD_IMAGE = 1;
private ImageView mIv;
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case LOAD_IMAGE:
Bitmap bitmap = (Bitmap) msg.obj;
mIv.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this, "加载图片成功", Toast.LENGTH_SHORT).show();
break;
case LOAD_ERROR:
System.out.println("LOAD_ERROR");
Toast.makeText(MainActivity.this, "加载图片失败", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return false;
}
});
private ArrayList<String> mPaths;
private int currentPosition = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mIv = findViewById(R.id.iv);
// 1.连接服务器,获取所有的图片链接信息
loadAllImagePath();
}
/**
* 获取全部图片资源路径
*/
private void loadAllImagePath() {
new Thread() {
@Override
public void run() {
// 浏览器发送一个get请求就可以把服务器的数据获取出来
// 用代码模拟一个http的get请求
try {
// 1.得到服务器资源的路径
URL url = new URL("http://192.168.1.130:8080/Day10/img/gaga.html");// 待会儿要解决一个问题,需要注意https/http以及虚拟机ip的问题 ;创建network_security_config.xml及在AndroidManifest.xml中添加数据才能进行http请求
// 2.通过这个路径打开浏览器的链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 3.设置请求方式为GET
conn.setRequestMethod("GET");// 注意请求方式只能大写,不能小写
// 为了有一个更好的用户ui提醒,获取服务器的返回状态码
int code = conn.getResponseCode();
if (code == 200) {// 返回成功
InputStream is = conn.getInputStream();
File file = new File(getCacheDir(), "info.txt");
FileOutputStream fos = new FileOutputStream(file);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
System.out.println("code == 200");
// 获取了所有的链接之后,就要去加载图片
beginLoadImage();
} else if (code == 404) {// 资源未找到
Message msg = Message.obtain();
msg.what = LOAD_ERROR;
msg.obj = "获取html失败,返回码:" + code;
mHandler.sendMessage(msg);
} else {// 其他响应码
Message msg = Message.obtain();
msg.what = LOAD_ERROR;
msg.obj = "服务器或网络异常,返回码:" + code;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 开始加载图片,在从服务器获取完毕资源路径之后执行
*/
private void beginLoadImage() {
try {
mPaths = new ArrayList<>();
File file = new File(getCacheDir(), "info.txt");
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
mPaths.add(line);
}
fis.close();
loadImageByPath(mPaths.get(currentPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过路径加载图片
*
* @param path
*/
private void loadImageByPath(final String path) {
new Thread() {
@Override
public void run() {
File file = new File(getCacheDir(), path.replace("/", "") + ".jpg");
if (file.exists() && file.length() > 0) {// 有缓存
System.out.println("通过缓存把图片获取出来...");
Message msg = Message.obtain();
msg.what = LOAD_IMAGE;
msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
mHandler.sendMessage(msg);
} else {// 没有缓存的话,就需要去下载
System.out.println("通过访问网络把图片资源获取出来");
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
// 内存中的图片
Bitmap bitmap = BitmapFactory.decodeStream(is);
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
is.close();
Message msg = Message.obtain();
msg.what = LOAD_IMAGE;
msg.obj = BitmapFactory.decodeFile(file.getAbsolutePath());
mHandler.sendMessage(msg);
} else {
Message msg = Message.obtain();
msg.what = LOAD_ERROR;
msg.obj = "获取图片失败,返回码:" + code;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what = LOAD_ERROR;
msg.obj = "获取图片失败";
mHandler.sendMessage(msg);
}
}
}
}.start();
}
/**
* 上一张图片
*
* @param view
*/
public void pre(View view) {
currentPosition--;
if (currentPosition < 0) {
currentPosition = mPaths.size() - 1;
}
loadImageByPath(mPaths.get(currentPosition));
}
/**
* 下一张图片
*
* @param view
*/
public void next(View view) {
currentPosition++;
if (currentPosition == mPaths.size()) {
currentPosition = 0;
}
loadImageByPath(mPaths.get(currentPosition));
}
}
<uses-permission android:name="android.permission.INTERNET"/>
注意:
app\src\main\res\xml路径下创建network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
AndroidManifest.xml 添加数据才能进行http请求
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.glsite.netimageviewer">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:networkSecurityConfig="@xml/network_security_config">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>