安卓开发-手机上显示tomcat中的图片

来源:互联网 发布:sql触发器类型 编辑:程序博客网 时间:2024/05/17 03:16

《1》.准备步骤:
1.在tomcat中的webapps中的ROOT项目下添加img文件夹,内有:picinfo.txt和图片,每张图片的url都在picinfo.txt中,如图:

这里写图片描述

《2》思路:

(2.1)定义成员变量:

2.1.1:图片控件  2.1.2:List对象存放每张图片的url2.1.3:定义显示图片的索引

(2.2)定义private void saveImageUrls() 函数,从tomcat中将picinfo.txt中的url加载到List中。

(2.3)定义private void loadImageByUrl(int currentIndex)函数,通过索引将图片从files或者tomcat中显示到ui上。

(2.4)为两个按钮添加点击事件函数,在函数中++/–索引并判断是否越界,再重新调用loadImageByUrl函数绘制ui.

《3》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" >"    <EditText        android:id="@+id/username_et"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:hint="请输入用户名:" />    <EditText        android:id="@+id/pwd_et"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:inputType="textPassword"        android:hint="请输入密码:" />    <Button        android:layout_width="wrap_content"         android:layout_height="wrap_content"        android:onClick="loginClick"        android:text="登录" /></LinearLayout>

《4》MainActivity中:

package com.m520it.findpicturemachine;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.Bitmap.CompressFormat;import android.graphics.BitmapFactory;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ImageView;/** * @author lq * *//** * @author lq * */public class MainActivity extends Activity {    private ImageView mImageView;//图片显示控件    private List<String> mImageURLs = new ArrayList<>();//存放tomcat/webapp/ROOT/image/picinfo.txt中的图片路径    private int mCurrentIndex;//用于对list的索引    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mImageView = (ImageView) findViewById(R.id.iv);        new Thread(){            public void run() {                saveImageUrls();                loadImageByUrl(mCurrentIndex);            };        }.start();    }    /**通过传入的索引,得到图片的路径,     * 若手机的files文件有该图片,从files中加载出图片并绘制到ui上,     * 若没有,从服务器中获取图片,先存放进files中,再显示到ui上     * @param currentIndex List中图片路径的索引     */    private void loadImageByUrl(int currentIndex) {        try {            String currentImageUrl = mImageURLs.get(currentIndex);            //判断files文件中是否有该图片,有就绘制到ui上            String imageName = getImageUrl(currentImageUrl);            File file = new File(getFilesDir(), imageName);            if(file.exists() && file.length() > 0){                final Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());                runOnUiThread(new Runnable() {                    public void run() {                        mImageView.setImageBitmap(map);                    }                });                return;            }            URL url = new URL(currentImageUrl);            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            if (conn.getResponseCode() == 200) {                InputStream inputStream = conn.getInputStream();                //从inputStream中加载出bitmap格式图片                final Bitmap bitMap = BitmapFactory.decodeStream(inputStream);                //通过bitmap存放图片到指定位置(files)中                FileOutputStream fos = openFileOutput(imageName, MODE_PRIVATE);                bitMap.compress(CompressFormat.PNG, 100, fos);                //显示图片到ui上                runOnUiThread(new Runnable() {                    public void run() {                        mImageView.setImageBitmap(bitMap);                    }                });            }        } catch (Exception e) {            e.printStackTrace();        }    }    /**得到图片的文件名     * @param string    图片的url地址     * @return  返回文件名     */    private String getImageUrl(String string) {        int index = string.lastIndexOf("/");        return string.substring(index + 1);    }    /**     * 将tomcat中webapps/ROOT/img/picinfo.txt中的图片url都加载到List集合中     */    private void saveImageUrls() {        try {            URL url = new URL(getImageUrls());            HttpURLConnection conn = (HttpURLConnection) url.openConnection();            int responseCode = conn.getResponseCode();            if (responseCode == 200) {                InputStream inputStream = conn.getInputStream();                BufferedReader reader = new BufferedReader(                        new InputStreamReader(inputStream));                String line = null;                while ((line = reader.readLine()) != null) {                    mImageURLs.add(line);                }            }        } catch (Exception e) {            e.printStackTrace();        }    }    public void preClick(View v) {        mCurrentIndex --;        if(mCurrentIndex < 0){            mCurrentIndex = mImageURLs.size() - 1;        }        new Thread(){            public void run() {                loadImageByUrl(mCurrentIndex);            };        }.start();    }    public void nextClick(View v) {        mCurrentIndex ++;        if(mCurrentIndex > mImageURLs.size() - 1){            mCurrentIndex = 0;        }        new Thread(){            public void run() {                loadImageByUrl(mCurrentIndex);            };        }.start();    }    private String getImageUrls() {        return "http://10.0.2.2:8080/img/picinfo.txt";    }}

《5》最后效果:
可点击两个按钮循环展示那几张图片

《6》总结:
(1)网络操作的通用步骤:

0.在ActivityMainfest.xml中添加

<uses-permission android:name="android.permission.INTERNET" />

1.创建URL

URL url = new URL(currentImageUrl);

2.打开链接

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

3.判断相应码是否为200

if (conn.getResponseCode() == 200) {业务操作}

4.获取服务器相应的输入流

InputStream inputStream = conn.getInputStream();

(2)网络中加载bitmap图片的常用操作:

1.加载图片(通过BitmapFactory直接从流中获取图片):

//1.1:从输入流中加载出bitmap图片Bitmap bitMap = BitmapFactory.decodeStream(inputStream);//1.2:从图片文件的绝对路径中加载成bitmap图片Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());//1.3:将系统中的资源文件转换为bitmap图片Bitmap bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_marka);

2.将获得的bitmap图片存放经files文件中(bitmap自带):

FileOutputStream fos = openFileOutput(imageName, MODE_PRIVATE);                bitMap.compress(CompressFormat.PNG, 100, fos);

3.显示图片到imageView控件上:

mImageView.setImageBitmap(bitMap);

(3)注意事项:

1.设定网络访问权限2.请求网络相关代码不能再主线程中添加,新建子线程处理:网络请求可能有延迟,MainActivity是负责渲染界面与和用户交互的,不能让网络请求的可能延迟影响到用户体验。3.设置ui应该回到主线程中,回到主线程中有两种方法:
    3.1:runOnUiThread(new Runnable(){在run方法中添加修改ui的代码})    3.2private Handler mHandler = new Handler(){         public void handleMessage(android.os.Message msg) {              添加修改ui的代码    }};

4.安卓手机访问tomcat中的资源地址不再是localhost或者电脑的ip,而是安卓映射为:10.0.2.2 。

原创粉丝点击