zoukankan      html  css  js  c++  java
  • 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);
    
        }
    }

    我要等一分钟了...

      

  • 相关阅读:
    6-Python爬虫-分布式爬虫/Redis
    ES 查询时 排序报错(fielddata is disabled on text fileds by default ... )解决方法
    Intellij Idea webstorm 激活
    Intellij Idea 配置jdk
    java 获取(格式化)日期格式
    js 跳转 XSS漏洞 预防
    CSS去掉背景颜色
    js对象无法当成参数传递 解决方法
    Elasticsearch java api
    java多条件查询SQL语句拼接的小技巧
  • 原文地址:https://www.cnblogs.com/scherrer/p/2941564.html
Copyright © 2011-2022 走看看