Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 從零開始搭建框架系列(1)

android 從零開始搭建框架系列(1)

編輯:關於Android編程

工作幾年發現自己沒留下啥東西,天天開發開發,沒總結過。 這次想總結下。故而寫這個系列的博客。希望對廣大的開發者有所幫助。


OK 首先先分析下 框架的作用,以及框架所應擁有的功能
框架有啥好處那,你只要寫了一次以後就可以重復利用了。
無非是拷貝過來拷貝過去。寫的框架必須簡單易懂。


功能以及分模塊:
1. 聯網 模塊
2. 數據緩存模塊。(緩存這裡比較重要,因為每次不肯能都去獲取新數據,太費流量了。)
3. 圖片聯網獲取並加載模塊。以及圖片的緩存
4. 數據庫模塊

ok 廢話不多說 上點干貨。下面是框架的結構圖

項目資料vc341b7PwtTYSHR0cENvbXBvbmVudHOjrMi7uvOw0cbk1tC1xEh0dHBNaW1lLmphcrD8t8W1vc/uxL/W0MilPC9wPg0KPGhyIC8+DQo8cD48c3Ryb25nPs/I0LS49sGqzfi/8rzco7podHRwbWFuYWdlci0g1eK49ta7ysfTw8C0warN+LXEPC9zdHJvbmc+PC9wPg0KPHByZSBjbGFzcz0="brush:java;"> package com.example.net.manager; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.util.EntityUtils; import com.example.net.BaseApplication; import com.example.net.Interface.IDownloadListener; import com.example.net.utils.LogUtil; import com.example.net.utils.NetWorkUtil; import android.net.http.AndroidHttpClient; /** * HttpManager 最基本的聯網請求 只做最基本的聯網操作 * * @author liuml * * 2015-3-12 下午3:14:27 */ public class HttpManager { private static final String TAG = "HttpManager"; public static HttpClient getDefaultHttpClient() { //xxxxx 輸入自己的項目名字 AndroidHttpClient httpClient = AndroidHttpClient.newInstance("xxxxx"); // HttpClient httpClient = new DefaultHttpClient(); return httpClient; } /** * 不帶參數的get請求 * * @param url * @param listener * @return */ public static String requestJsonWithGet(String url, IDownloadListener listener) { // 判斷網路狀態 if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) { if (listener != null) { listener.onNetworkDisconnect(); } return null; } String requestResult = null; HttpClient httpClient = getDefaultHttpClient(); HttpGet httpRequest = new HttpGet(url); LogUtil.d(TAG, "url = " + url); try { HttpResponse response = httpClient.execute(httpRequest); int statusCode = response.getStatusLine().getStatusCode(); LogUtil.d(TAG, "服務器返回碼" + statusCode); if (HttpStatus.SC_OK == statusCode) { HttpEntity entity = response.getEntity(); if (entity != null) { requestResult = EntityUtils.toString(entity); if (listener != null) { listener.onDownloadSuccessed(requestResult); } } else { if (listener != null) { listener.onDownloadFailed(); } } } else { if (listener != null) { listener.onDownloadFailed(); } } } catch (ClientProtocolException e) { e.printStackTrace(); listener.onDownloadFailed(); } catch (IOException e) { e.printStackTrace(); listener.onDownloadFailed(); } finally { if (httpClient instanceof AndroidHttpClient) { ((AndroidHttpClient) httpClient).close(); } } return requestResult; } /** * 帶參數的get請求 * * @param url * @param getParameters * @param listener * @return */ public static String requestJsonWithGet(String url, List parameters, IDownloadListener listener) { if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) { if (listener != null) { listener.onNetworkDisconnect(); } return null; } String murl = url + "?" + NameValuePair2String(parameters); LogUtil.d(TAG, "帶參數的Get請求(從網絡)= " + murl); String requestResult = null; HttpClient httpClient = getDefaultHttpClient(); HttpGet httpRequest = new HttpGet(murl); try { HttpResponse response = httpClient.execute(httpRequest); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { HttpEntity entity = response.getEntity(); if (entity != null) { requestResult = EntityUtils.toString(entity); if (listener != null) { listener.onDownloadSuccessed(requestResult); } } else { if (listener != null) { listener.onDownloadFailed(); } } } else { if (listener != null) { listener.onDownloadFailed(); } } } catch (ClientProtocolException e) { if (listener != null) { listener.onDownloadFailed(); } e.printStackTrace(); } catch (IOException e) { if (listener != null) { listener.onDownloadFailed(); } e.printStackTrace(); } finally { if (httpClient instanceof AndroidHttpClient) { ((AndroidHttpClient) httpClient).close(); } } return requestResult; } /** * 帶參數的Post請求 * * @param url * @param postParameters * @param listener * @return */ public static String requestJsonWithPost(String url, List postParameters, IDownloadListener listener) { LogUtil.d(TAG, "requestJsonWithPost"); if (BaseApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) { if (listener != null) { listener.onNetworkDisconnect(); } return null; } String requestResult = null; HttpPost httpRequest = new HttpPost(url); if (postParameters != null && postParameters.size() > 0) { UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(postParameters, "utf-8"); httpRequest.setEntity(entity); } catch (UnsupportedEncodingException e) { if (listener != null) { LogUtil.d(TAG, "UserLogin UnsupportedEncodingException, e = " + e); listener.onDownloadFailed(); } return null; } } BasicHttpParams params = new BasicHttpParams(); params.setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 30000); HttpClient httpClient = new DefaultHttpClient(params); HttpResponse response = null; try { response = httpClient.execute(httpRequest); int statusCode = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == statusCode) { HttpEntity entity = response.getEntity(); requestResult = EntityUtils.toString(entity); if (listener != null) { LogUtil.d(TAG, "UserLogin onDownloadSuccessed"); listener.onDownloadSuccessed(requestResult); } } else { if (listener != null) { LogUtil.d(TAG, "UserLogin HttpStatus.SC_OK != statusCode"); LogUtil.d(TAG, "狀態碼 = " + statusCode); listener.onDownloadFailed(); } } } catch (Exception e) { if (listener != null) { LogUtil.d(TAG, "UserLogin HttpStatus.SC_OK != statusCode"); listener.onDownloadFailed(); } e.printStackTrace(); } finally { if (httpClient instanceof AndroidHttpClient) { ((AndroidHttpClient) httpClient).close(); } } return requestResult; } /** * 參數轉化 * * @param parameters * @return */ private static String NameValuePair2String(List parameters) { StringBuilder builder = new StringBuilder(); for (NameValuePair item : parameters) { builder.append(item.getName()); builder.append("="); builder.append(item.getValue()); builder.append("&"); } builder.deleteCharAt(builder.length() - 1); return builder.toString(); } }


然後我創建一個json管理器 jsonmanager

jsonManager主要的功能有:

創建線程池,處理聯網請求,異步加載。 判斷網絡狀態,以及 調用存儲json數據的方法。 。。反正就是一系列判斷。
package cn.com.psy.xinhaijiaoyu.mamager;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.NameValuePair;

import android.content.Context;
import cn.com.psy.xinhaijiaoyu.XinHaiApplication;
import cn.com.psy.xinhaijiaoyu.Interface.IDownloadListener;
import cn.com.psy.xinhaijiaoyu.cache.JsonCacheManager;
import cn.com.psy.xinhaijiaoyu.util.LogUtil;
import cn.com.psy.xinhaijiaoyu.util.NetWorkUtil;

/**
 * json 數據管理
 * 
 * @author liuml 2014-2-27
 * 
 */
public class JsonManager {
    private static final String TAG = "JsonManager";
    private JsonCacheManager mJsonCacheManager;
    private ExecutorService mExecutorService;
    private static final int THREAD_POOL_SIZE = 5;

    public JsonManager(Context context) {
        mJsonCacheManager = new JsonCacheManager(context);
        mExecutorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
    }

    /**
     * 沒有參數的get請求
     * 
     * @param url
     * @param listener
     */
    public void loadJsonByGet(String url, IDownloadListener listener) {
        loadJsonByGet(url, listener, false);
    }

    /**
     * 有參數的get請求,無服務器判斷
     * 
     * @param url
     * @param parameters
     * @param listener
     */
    public void loadJsonByGet(final String url, final List parameters, final IDownloadListener listener) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByHttpGet(url, parameters, listener);
            }
        });
    }

    /**
     * 有參數的get請求 有服務器判斷
     * 
     * @param url
     * @param parameters
     * @param listener
     * @param fromServer
     */
    public void loadJsonByGet(final String url, final List parameters, final IDownloadListener listener, final Boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByJsonGet(url, parameters, listener, fromServer);
            }
        });
    }

    public void loadJsonByGet(final String url, final List parameters, final IDownloadListener listener, final Boolean fromServer, final long timeout) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByJsonGet(url, parameters, listener, fromServer, timeout);
            }
        });
    }

    /**
     * 獲取數據get請求
     * 
     * @param url
     * @param parameters
     * @param listener
     */
    protected void loadJsonByHttpGet(String url, List parameters, IDownloadListener listener) {
        String json = null;
        json = loadJsonFromServerByHttpGet(url, parameters, listener);
        LogUtil.d(TAG, "loadJsonByHttpGet==" + json);
    }

    /**
     * 沒有參數的get請求
     * 
     * @param url
     * @param listener
     * @param fromServer
     */
    public void loadJsonByGet(final String url, final IDownloadListener listener, final boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByHttpGet(url, listener, fromServer);
            }
        });
    }

    /**
     * 無參數的post請求
     * 
     * @param url
     * @param listener
     * @param fromServer
     */
    public void loadJsonByPost(final String url, final IDownloadListener listener, final boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByHttpPost(url, listener, fromServer);
            }
        });
    }

    public void loadJsonByHttpGet(String url, IDownloadListener listener, boolean fromServer) {
        String json = null;
        if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
            json = getJsonFromCacheFile(url);
            if (json != null) {
                if (listener != null) {
                    listener.onDownloadSuccessed(json);
                }
                return;
            }
        }

        json = loadJsonFromServerByHttpGet(url, listener);
        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(url, json);
        }
    }

    public void loadJsonByHttpPost(String url, IDownloadListener listener, boolean fromServer) {
        String json = null;
        if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
            json = getJsonFromCacheFile(url);
            if (json != null) {
                if (listener != null) {
                    listener.onDownloadSuccessed(json);
                }
                return;
            }
        }

        json = loadJsonFromServerByHttpPost(url, listener);
        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(url, json);
        }
    }

    private String loadJsonFromServerByHttpGet(String url, IDownloadListener listener) {
        return HttpManager.requestJsonWithGet(url, listener);
    }

    private String loadJsonFromServerByHttpGet(String url, List parameters, IDownloadListener listener) {
        return HttpManager.requestJsonWithGet(url, parameters, listener);
    }

    private String loadJsonFromServerByHttpPost(String url, IDownloadListener listener) {
        return HttpManager.requestJsonWithPost(url, listener);
    }

    /**
     * 有參數的post請求
     * @param url
     * @param parameters
     * @param listener
     */
    public void loadJsonByPost(String url, List parameters, IDownloadListener listener) {
        loadJsonByPost(url, parameters, listener, false);
    }

    public void loadJsonByPost(final String url, final List parameters, final IDownloadListener listener, final boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                loadJsonByHttpPost(url, parameters, listener);
            }
        });
    }

    // 直接訪問網絡
    public void loadJsonByHttpPost(String url, List parameters, IDownloadListener listener) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;

        }

        String json = null;
        String urlParams = url + "?" + NameValuePair2String(parameters);

        LogUtil.d(TAG, "post請求 url = " + urlParams);
        json = loadJsonFromServerByHttpPost(url, parameters, listener);
        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(urlParams, json);
        }
    }

    private String loadJsonFromServerByHttpPost(String url, List parameters, IDownloadListener listener) {
        return HttpManager.requestJsonWithPost(url, parameters, listener);
    }

    private String getJsonFromCacheFile(String url) {
        return mJsonCacheManager.getJsonFromDiskCache(url);
    }

    private String getJsonFromCacheFile(String url, long timeout) {
        return mJsonCacheManager.getJsonFromDiskCache(url, timeout);
    }

    private String NameValuePair2String(List parameters) {
        StringBuilder builder = new StringBuilder();
        for (NameValuePair item : parameters) {
            builder.append(item.getName());
            builder.append("=");
            builder.append(item.getValue());
            builder.append("&");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

    /**
     * 上傳圖片
     * 
     * @param url
     * @param parameters
     * @param avartarFile
     * @param listener
     */
    public void uploadUserAvartar(final String url, final List parameters, final File avartarFile, final IDownloadListener listener) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                uploadUserAvartarByPost(url, parameters, avartarFile, listener);
            }
        });

    }

    protected void uploadUserAvartarByPost(String url, List parameters, File avartarFile, IDownloadListener listener) {
        HttpManager.uploadUserAvartar(url, parameters, avartarFile, listener);
    }

    public void uploadMultiPics(final String url, final List parameters, final List picsList, final IDownloadListener listener, final boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;
        }

        mExecutorService.execute(new Runnable() {

            @Override
            public void run() {
                uploadMultiPicsByPost(url, parameters, picsList, listener);
            }
        });

    }

    protected void uploadMultiPicsByPost(String url, List parameters, List picsList, IDownloadListener listener) {
        HttpManager.uploadMultiPics(url, parameters, picsList, listener);
    }

    public void loadJsonByJsonPost(String url, List parameters, IDownloadListener listener, boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;

        }

        String json = null;
        String urlParams = url + NameValuePair2String(parameters);
        LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
        if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
            json = getJsonFromCacheFile(urlParams);
            LogUtil.d(TAG, "從cache 中 json " + json);
            if (json != null) {
                if (listener != null) {
                    listener.onDownloadSuccessed(json);
                }
                return;
            }
        }
        json = loadJsonFromServerByHttpPost(url, parameters, listener);
        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(urlParams, json);
        }
    }

    public void loadJsonByJsonGet(String url, List parameters, IDownloadListener listener, boolean fromServer) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;

        }

        String json = null;
        String urlParams = url + NameValuePair2String(parameters);
        LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
        if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
            json = getJsonFromCacheFile(urlParams);
            LogUtil.d(TAG, "從cache 中 json " + json);
            if (json != null) {
                if (listener != null) {
                    listener.onDownloadSuccessed(json);
                }
                return;
            }
        }
        json = loadJsonFromServerByHttpGet(url, parameters, listener);

        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(urlParams, json);
        }
    }

    public void loadJsonByJsonGet(String url, List parameters, IDownloadListener listener, boolean fromServer, long timeout) {
        if (url == null) {
            if (listener != null) {
                listener.onDownloadFailed();
            }
            return;

        }

        String json = null;
        String urlParams = url + NameValuePair2String(parameters);
        LogUtil.d(TAG, "url = " + url + "?" + NameValuePair2String(parameters));
        if (!fromServer || XinHaiApplication.mNetworkState == NetWorkUtil.STATE_DISCONNECT) {
            json = getJsonFromCacheFile(urlParams, timeout);
            LogUtil.d(TAG, "從cache 中 json " + json);
            if (json != null) {
                if (listener != null) {
                    listener.onDownloadSuccessed(json);
                }
                return;
            }
        }
        json = loadJsonFromServerByHttpGet(url, parameters, listener);

        if (json != null) {
            mJsonCacheManager.addJsonToDiskCache(urlParams, json);
        }
    }
}

這是json管理器。 在哪裡調用他呢?

這時候我寫個類DataManager 在這裡調用他

package com.example.net.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.example.net.Interface.IDownloadListener;
import com.example.net.config.ApiHttpConfig;
import com.example.net.config.MyParameters;
import com.example.net.utils.LogUtil;

/**
 * 數據管理
 * 
 * @author liuml 2014-2-27
 * 
 */
public class DataManager {
    private static final String TAG = "DataManager";
    // private static DataManager mInstance;
    private JsonManager mJsonManager;

    public DataManager(JsonManager jsonManager) {
        mJsonManager = jsonManager;
    }

    /**
     * 登陸接口
     * 
     * @param username
     *            用戶名
     * @param passwd
     *            密碼
     * @param imsi
     *            手機imsi
     * @param listener
     *            回調接口
     * @param formServer
     *            是否從服務器上獲取(默認為false 如果本地沒有數據則從網上獲取, 如果為true 則強制從網上獲取)
     */
    public void login(String username, String passwd, String imsi, IDownloadListener listener, boolean formServer) {
        String url = ApiHttpConfig.getInstance().loginApi();
        LogUtil.d(TAG, "login url ========================== " + url);
        List parameters = MyParameters.getInstance().loginParameters(username, passwd, imsi);
        mJsonManager.loadJsonByPost(url, parameters, listener, formServer);
    }

}

這裡我也只是做個登陸接口。其他接口想怎麼寫就怎麼寫
對了 還有參數的添加。添加的話需要再寫一個類。

package com.example.net.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.example.net.utils.LogUtil;

public class MyParameters extends ApiHttpConfig{
    private static MyParameters Parameters = new MyParameters();

    public static MyParameters getInstance() {
        return Parameters;
    }

    /**
     * 登陸參數
     * @param username
     * @param passwd
     * @param imsi
     * @return
     */
    public List loginParameters(String username, String passwd, String imsi) {

        ArrayList parameters = new ArrayList();
        if (username == null) {
            username = "";
        }
        if (passwd == null) {
            passwd = "";
        }
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("password", passwd));
        parameters.add(new BasicNameValuePair("imsi", imsi));

        LogUtil.d(TAG + "loginParameters :", parameters.toString());
        return parameters;
    }
}

這個類繼承ApiHttpConfig 這個類是用作保存接口的地方

package com.example.net.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.example.net.utils.LogUtil;

/**
 * 
 * @author liuml
 * 
 *         2015-4-22 上午11:58:11
 */
public class ApiHttpConfig {

    private static ApiHttpConfig apiConfig = new ApiHttpConfig();

    public static final String DefaultParserUrl = "http://192.168.1.1/api/mapi";
    // 登錄
    public static final String LOGIN_PART_STRING = "/Login";

    public static final String PARENT_AND_CHILD_REGIST = "/ParentRegist";
    protected static final String TAG = "ApiHttpConfig";

    public static ApiHttpConfig getInstance() {
        return apiConfig;
    }

    public String loginApi() {
        return DefaultParserUrl + LOGIN_PART_STRING;
    }

}

今天就暫時寫這麼多吧。。ok
裡面還有些緩存模塊的東西 我明天再加上去吧。。等我全部寫完了在吧框架代碼發上去

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved