1. 程式人生 > >安卓開發-手機上顯示tomcat中的圖片

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

《1》.準備步驟:
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中

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