安卓開發-手機上顯示tomcat中的圖片

安卓開發-手機上顯示tomcat中的圖片。準備步驟:
1.在tomcat中的webapps中的ROOT項目下添加img文件夾,內有:picinfo.txt和圖片,每張圖片的url都在picinfo.txt中,如圖:

這裡寫圖片描述

《2》思路:

(2.1)定義成員變量:

2.1.1:圖片控件  
2.1.2:List對象存放每張圖片的url
2.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中

"

    
    

《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 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 "https://10.0.2.2:8080/img/picinfo.txt";
    }
}

《5》最後效果:
可點擊兩個按鈕循環展示那幾張圖片

《6》總結:
(1)網絡操作的通用步驟:

0.在ActivityMainfest.xml中添加

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直接從流中獲取圖片):

Bitmap bitMap = BitmapFactory.decodeStream(inputStream);

2.將獲得的bitmap圖片存放經files文件中(bitmap自帶):

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

3.顯示圖片到imageView控件上:

mImageView.setImageBitmap(bitMap);

4.通過圖片所在的絕對路徑加載出bitmap圖片:

Bitmap map = BitmapFactory.decodeFile(file.getAbsolutePath());

(3)註意事項:

1.設定網絡訪問權限

2.請求網絡相關代碼不能再主線程中添加,新建子線程處理:網絡請求可能有延遲,MainActivity是負責渲染界面與和用戶交互的,不能讓網絡請求的可能延遲影響到用戶體驗。

3.設置ui應該回到主線程中,回到主線程中有兩種方法:
    3.1:runOnUiThread(new Runnable(){在run方法中添加修改ui的代碼})

    3.2:private Handler mHandler = new Handler(){
         public void handleMessage(android.os.Message msg) {
              添加修改ui的代碼
    }
};

4.安卓手機訪問tomcat中的資源地址不再是localhost或者電腦的ip,而是安卓映射為:10.0.2.2 。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *