Android客戶端獲取服務器的json數據(一)


在上學期(大三),實驗室老師給我們一個小項目,做一個手機購物的客戶端,我負責寫服務器,服務器采用ssh+jpa,返回json數據給客戶端。但是負責寫Client的童鞋他們沒有太給力,於是,我又抱着練習的心態去寫Client。唉,往事已矣,老師說這個項目是個練習項目...結果,我們就沒有練習下去了,只做了一個半成品。逝者如斯夫,不舍晝夜,這里是為了紀念那些日子和當時用到的開發模式。

1.有一些程序截圖,UI是我的大問題啊。

  

     

2.采用mvc模式,處理Client業務與UI更新。畫不來圖,直接上代碼理解。

  ⑴定義一個IMActivity接口,聲明兩個抽象方法,項目中與UI有關的activity都要implements該接口

    public abstract void init();//實現數據初始化

    public abstract void refresh(Object ... param);//當獲取到網絡數據后,更新UI.

  ⑵開發一個業務處理中心,一個后台Service。功能為獲取網絡數據,處理線程通信,發送更新UI的消息對象。

  ⑶定義一個任務bean,用於新建任務,任務類型:用戶登錄,獲取產品類別,獲取產品等等。

  ⑷UI設計

  ⑸獲取網絡json數據的輔助類

  

3.具體代碼過程

  ⑴根據不同的層的功能,建立程序包結構。

  

  ⑵activity接口

  

package com.mpros.service.model;

/***
 * 本系統的所有activity父接口,實現activity初始化和Ui更新
 * @author Scherrer
 *
 */
public interface IMActivity {
    
    public abstract void init();
    public abstract void refresh(Object ...param);
}

  ⑶Service服務

  

View Code
package com.mpros.service;

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

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.mpros.activity.R;
import com.mpros.activity.classify.ChildClassifyActivity;
import com.mpros.activity.classify.ClassifyActivity;
import com.mpros.activity.classify.ProductListActivity;
import com.mpros.bean.Task;
import com.mpros.bean.product.ProductType;
import com.mpros.service.json.ProductTypeService;
import com.mpros.service.model.IMActivity;
import com.mpros.service.model.ProductAction;
import com.mpros.util.HttpUtil;

/**
 * 實現業務調度的核心邏輯服務
 */
public class MainService extends Service implements Runnable {
    // 保存所有的activity
    public static ArrayList<Activity> allActivities = new ArrayList<Activity>();
    // 保存前一個Activity的編號
    public static int lastAcvityId;
    // 所以任務
    public static ArrayList<Task> allTasks = new ArrayList<Task>();
    // 循環控制變量
    private boolean isrun = true;

    // 保存產品類型logo
    public static HashMap<Integer, BitmapDrawable> allTypeIcon = new HashMap<Integer, BitmapDrawable>();

    // 保存二級分類logo
    public static HashMap<Integer, BitmapDrawable> allChildTypeIcon = new HashMap<Integer, BitmapDrawable>();

    // 保存產品logo
    public static HashMap<Integer, BitmapDrawable> allProductLogo = new HashMap<Integer, BitmapDrawable>();
    //產品的所有樣式
    //public static HashMap<Integer, ArrayList<BitmapDrawable>> allProductDescImage = new HashMap<Integer, ArrayList<BitmapDrawable>>();

    /**
     * 在集合里,通過name獲取Activity對象
     * 
     * @param name
     * @return Activity
     */
    public static Activity getActivityByName(String name) {
        for (Activity a : allActivities) {
            if (a.getClass().getName().indexOf(name) >= 0) {
                return a;
            }
        }
        return null;
    }

    /**
     * 新建任務
     * 
     * @param task
     */
    public static void newTask(Task task) {
        // 添加一個任務
        allTasks.add(task);
    }

    /*********
     * 啟動線程
     */
    @Override
    public void run() {
        while (isrun) {
            Task lastTask = null;
            if (allTasks.size() > 0) {
                synchronized (allTasks) {
                    // 獲取任務
                    lastTask = allTasks.get(0);
                    // 執行任務

                    doTask(lastTask);
                }
            }
            // 如果沒有任務,則等待2000ms,繼續獲取任務
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /************************
     * 很據任務ID,執行該任務
     * 
     * @param task
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void doTask(Task task) {

        Message msg = new Message();
        System.out.println("任務編號: " + task.getTaskId());
        msg.what = task.getTaskId();
        try {
            switch (task.getTaskId()) {

            case Task.TASK_GET_PRODUCTTYPE:// 獲取產品類型

                // 傳遞消息和數據
                List<ProductType> types = ProductTypeService
                        .getTypesFromJson(ProductAction.GET_PRODUCTYPE_ACTION);
                if (types != null) {

                    if (allTypeIcon == null) {
                        allTypeIcon = new HashMap<Integer, BitmapDrawable>();
                    }

                    // 獲取logo
                    for (ProductType type : types) {
                        BitmapDrawable bd = allTypeIcon.get(type.getTypeid());
                        if (bd == null) {
                            HashMap param = new HashMap();
                            param.put("typeid", type.getTypeid());
                            param.put("typelogo", ProductAction.BASE_ACTION
                                    + type.getTypelogo());
                            Log.i(Task.Logger + type.getTypeid(),
                                    ProductAction.BASE_ACTION
                                            + type.getTypelogo());
                            Task tk = new Task(Task.GET_TYPE_LOGO, param);
                            MainService.newTask(tk);
                        }
                    }

                    msg.obj = types;
                }

                break;
            case Task.GET_TYPE_LOGO:

                Integer typeid = (Integer) task.getTaskParam().get("typeid");
                BitmapDrawable drawable = HttpUtil.getImageFromUrl(task
                        .getTaskParam().get("typelogo").toString());
                // 添加logo到集合里
                allTypeIcon.put(typeid, drawable);
                break;

            case Task.TASK_GET_CHILDTYPE_LOGO:
                Integer childtypeid = (Integer) task.getTaskParam().get(
                        "typeid");

                BitmapDrawable childdrawable = HttpUtil.getImageFromUrl(task
                        .getTaskParam().get("typelogo").toString());
                // 添加logo到集合里
                allChildTypeIcon.put(childtypeid, childdrawable);

                break;

            case Task.TASK_GET_PRODUCT_IMAGE:

                Integer productid = (Integer)task.getTaskParam().get("productid");
                BitmapDrawable productlogo = HttpUtil.getImageFromUrl(task.getTaskParam().get("productlogo").toString());
                
                allProductLogo.put(productid, productlogo);
                break;
            }

        } catch (Exception e) {
            msg.what = -100;
            e.printStackTrace();
        }
        handler.sendMessage(msg);
        allTasks.remove(task);// 執行完任務,則移出該任務
    }

    // 當前服務的子線程Handler,負責處理更新UI操作
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.i(Task.Logger, "UI 更新編號:" + msg.what);
            switch (msg.what) {

            case Task.TASK_GET_PRODUCTTYPE:

                IMActivity ia = (ClassifyActivity) getActivityByName("ClassifyActivity");
                ia.refresh(ClassifyActivity.GET_TYPE_SUCCESS, msg.obj);
            case Task.GET_TYPE_LOGO:

                IMActivity ia1 = (ClassifyActivity) getActivityByName("ClassifyActivity");
                ia1.refresh(ClassifyActivity.REFRESH_TYPE_LOGO, msg.obj);
                break;

            case Task.TASK_GET_CHILDTYPE_LOGO:
                IMActivity ia2 = (ChildClassifyActivity) getActivityByName("ChildClassifyActivity");
                ia2.refresh(ChildClassifyActivity.REFRESH_CHILDTYPE_LOGO,
                        msg.obj);
                break;
            case Task.TASK_GET_PRODUCT_IMAGE:
                IMActivity ia3 = (ProductListActivity)getActivityByName("ProductListActivity");
                ia3.refresh(ProductListActivity.REFRESH_PRODUCT_LOGO);
                break;
            }
        }

    };

    @Override
    public void onCreate() {
        super.onCreate();
        isrun = true;
        new Thread(this).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isrun = false;
    }

    /*******************
     * 網絡連接出錯,提示對話框
     * 
     * @param context
     */
    public static void alerNetErr(final Context context) {

        // 對話框
        AlertDialog.Builder ab = new AlertDialog.Builder(context);
        ab.setTitle(R.string.NoRouteToHostException);
        ab.setMessage(R.string.NoSignalException);
        // 設置操作對象
        ab.setPositiveButton(R.string.apn_is_wrong1_setnet,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 取消對話框
                        dialog.cancel();
                        // 打開網絡設置Activity
                        Intent it = new Intent(
                                android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        context.startActivity(it);
                    }
                });
        ab.setNegativeButton(R.string.apn_is_wrong1_exit,
                new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 取消對話框
                        dialog.cancel();
                        // 退出程序
                        // exitApp(context);
                    }
                });
        // 顯示
        ab.create().show();
    }

    /************************
     * 提示對話框
     * 
     * @param context
     */
    public static void promptExit(final Context context) {
        // 通過Inflater對象把布局文件壓縮為視圖
        LayoutInflater flater = LayoutInflater.from(context);
        View exitView = flater.inflate(R.layout.exitdialog, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        // 改變對話框的默認布局,用已有視圖來覆蓋
        builder.setView(exitView);

        builder.setPositiveButton(R.string.confirm_exit,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitApp(context);
                    }
                });

        builder.setNegativeButton(R.string.apn_is_wrong1_exit, null);

        // 顯示對話框
        builder.show();

    }

    /**************
     * 退出程序
     */
    public static void exitApp(Context context) {

        // 出棧所有Activity
        if (allActivities != null) {
            for (Activity ac : allActivities) {
                ac.finish();
            }
        }

        // 關閉服務
        Intent it = new Intent("com.xl.service.MainService");
        context.stopService(it);
        System.exit(0);

    }
}

我要等一分鍾了...

 

 

 

  

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM