谷歌电子市场笔记2

把所有共性的代码提取到BaseFragment 再把一部分代码 摘取到LoadingPage帧布局中

线程池的原理

    public class ThreadPool {
        int maxCount = 3;
        AtomicInteger count =new AtomicInteger(0);// 当前开的线程数  count=0
        LinkedList<Runnable> runnables = new LinkedList<Runnable>();

        public void execute(Runnable runnable) {
            runnables.add(runnable);
            if(count.incrementAndGet()<=3){
                createThread();
            }
        }
        private void createThread() {
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    while (true) {
                        // 取出来一个异步任务
                        if (runnables.size() > 0) {
                            Runnable remove = runnables.remove(0);
                            if (remove != null) {
                                remove.run();
                            }
                        }else{
                            //  等待状态   wake();
                        }
                    }
                }
            }.start();
        }
    }

线程池的用法

        /**
         * 执行任务
         * @param runnable
         */
        public void execute(Runnable runnable) {
            if (pool == null) {
                // 创建线程池
                /*
                 * 1. 线程池里面管理多少个线程2. 如果排队满了, 额外的开的线程数3. 如果线程池没有要执行的任务 存活多久4.
                 * 时间的单位 5 如果 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队
                 */
                pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                        time, TimeUnit.MILLISECONDS,
                        new LinkedBlockingQueue<Runnable>(10));
            }
            pool.execute(runnable); // 调用线程池 执行异步任务
        }
        /**
         * 取消任务
         * @param runnable
         */
        public void cancel(Runnable runnable) {
            if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {
                pool.remove(runnable); // 取消异步任务
            }
        }

缓存到本地

private void saveLocal(String json, int index) {

    BufferedWriter bw = null;
    try {
        File dir=FileUtils.getCacheDir();
        //在第一行写一个过期时间 
        File file = new File(dir, "home_" + index); // /mnt/sdcard/googlePlay/cache/home_0
        FileWriter fw = new FileWriter(file);
         bw = new BufferedWriter(fw);
        bw.write(System.currentTimeMillis() + 1000 * 100 + "");
        bw.newLine();// 换行
        bw.write(json);// 把整个json文件保存起来
        bw.flush();
        bw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        IOUtils.closeQuietly(bw);
    }
}

读取本地缓存

    private String loadLocal(int index) {
        //  如果发现文件已经过期了 就不要再去复用缓存了
        File dir=FileUtils.getCacheDir();// 获取缓存所在的文件夹
        File file = new File(dir, "home_" + index); 
        try {
            FileReader fr=new FileReader(file);
            BufferedReader br=new BufferedReader(fr);
            long outOfDate = Long.parseLong(br.readLine());
            if(System.currentTimeMillis()>outOfDate){
                return null;
            }else{
                String str=null;
                StringWriter sw=new StringWriter();
                while((str=br.readLine())!=null){

                    sw.write(str);
                }
                return sw.toString();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

解析json

见到大括号{} 就用JsonObject ,见到中括号[]就是JsonArray

private List<AppInfo> paserJson(String json) {
    List<AppInfo> appInfos=new ArrayList<AppInfo>();
    try {
        JSONObject jsonObject=new JSONObject(json);
        JSONArray jsonArray = jsonObject.getJSONArray("list");
        for(int i=0;i<jsonArray.length();i++){
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            long id=jsonObj.getLong("id");
            String name = jsonObj.getString("name");
            String packageName=jsonObj.getString("packageName");
            String iconUrl = jsonObj.getString("iconUrl");
            float stars=Float.parseFloat(jsonObj.getString("stars"));
            long size=jsonObj.getLong("size");
            String downloadUrl = jsonObj.getString("downloadUrl");
            String des = jsonObj.getString("des");
            AppInfo info=new AppInfo(id, name, packageName, iconUrl, stars, size, downloadUrl, des);
            appInfos.add(info);
        }
        return appInfos;

    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}

RatingBar

和水平进度条非常相似

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background" android:drawable="@drawable/rating_small_empty" />
    <item android:id="@+android:id/secondaryProgress" android:drawable="@drawable/rating_small_half" />
    <item android:id="@+android:id/progress" android:drawable="@drawable/rating_small_full" />
</layer-list>

加载服务器的图片

三级缓存

  1. 网络 本地 内存
  2. 加载内存 lru 算法

    public class BitmapHelper { private BitmapHelper() { }

    private static BitmapUtils bitmapUtils;
    
    /**
     * BitmapUtils不是单例的 根据需要重载多个获取实例的方法
     * 
     * @param appContext
     *            application context
     * @return
     */
    public static BitmapUtils getBitmapUtils() {
        if (bitmapUtils == null) {
            // 第二个参数 缓存图片的路径 // 加载图片 最多消耗多少比例的内存 0.05-0.8f
            bitmapUtils = new BitmapUtils(UiUtils.getContext(), FileUtils
                    .getIconDir().getAbsolutePath(), 0.3f);
        }
        return bitmapUtils;
    }
    

    }

    public View createSuccessView() {
        ListView listView=new ListView(UiUtils.getContext());
        listView.setAdapter(new HomeAdapter());
        bitmapUtils = BitmapHelper.getBitmapUtils();
        // 第二个参数 慢慢滑动的时候是否加载图片 false  加载   true 不加载
        //  第三个参数  飞速滑动的时候是否加载图片  true 不加载 
        listView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
        bitmapUtils.configDefaultLoadingImage(R.drawable.ic_default);  // 设置如果图片加载中显示的图片
        bitmapUtils.configDefaultLoadFailedImage(R.drawable.ic_default);// 加载失败显示的图片
    
        return listView;
    }
    

BaseListView

public class BaseListView extends ListView {

    public BaseListView(Context context) {
        super(context);
        init();
    }

    public BaseListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public BaseListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
//      setSelector  点击显示的颜色
//      setCacheColorHint  拖拽的颜色
//      setDivider  每个条目的间隔 的分割线    
        this.setSelector(R.drawable.nothing);  // 什么都没有
        this.setCacheColorHint(R.drawable.nothing);
        this.setDivider(UiUtils.getDrawalbe(R.drawable.nothing));
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值