AppStoreDemo

公司提的需求,在App中嵌入一个App下载模块,支持下载,安装,暂停,继续等操作。
使用的是Xutils框架,现在把这个功能提取出来了。
关于Xutils:http://blog.csdn.net/hello_12413/article/details/47032131
项目:https://github.com/SunnyLine/AppStoreDemo
页面不多,一共三,一个App列表,一个详情页,一个下载管理页面。效果如下:
这里写图片描述

下面贴上App列表的代码:

package com.example.appstoredemo.activity;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.example.appstoredemo.R;
import com.example.appstoredemo.adapter.AppRecommendAdapter;
import com.example.appstoredemo.bean.AppBean;
import com.example.appstoredemo.utils.AssetsHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

public class MainActivity extends BaseActivity implements OnItemClickListener {
    List<AppBean> mList;
    @ViewInject(R.id.lv)
    private ListView lv;
    private AppRecommendAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
        setTitle("App列表");
        initJson();
        adapter = new AppRecommendAdapter(this, mList);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    // 读取assets文件夹中数据
    public void initJson() {
        AssetsHelper assetsHelper = new AssetsHelper();
        mList = new ArrayList<AppBean>();
        String json = assetsHelper.getFromAssets(this, "json");
        try {
            JSONArray array = new JSONObject(json).optJSONArray("apklist");
            if (null != array) {
                for (int i = 0; i < array.length(); i++) {
                    AppBean appBean = new AppBean();
                    appBean.parserJson(array.optJSONObject(i));
                    mList.add(appBean);
                }
            }
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AppBean appBean = (AppBean) parent.getItemAtPosition(position);
        Intent intent = new Intent(this, AppDetialActivity.class);
        intent.putExtra("data", appBean);
        startActivity(intent);
    }
}

Item布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_item_shape"
    android:descendantFocusability="blocksDescendants"
    android:padding="10dip" >

    <FrameLayout
        android:id="@+id/frame1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" >

        <ImageView
            android:id="@+id/img_icon"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dip"
        android:layout_toLeftOf="@+id/rel1"
        android:layout_toRightOf="@+id/frame1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_company"
            style="@style/txt_gay_14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="5dip"
            android:singleLine="true"
            android:text="新浪网络技术股份有限公司" />

        <TextView
            android:id="@+id/tv_title"
            style="@style/txt_black_18"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:text="新浪微博" />

        <TextView
            android:id="@+id/tv_size"
            style="@style/txt_black_14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dip"
            android:singleLine="true"
            android:text="34.2M" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rel1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" >

        <Button
            android:id="@+id/btn_down"
            style="@style/txt_white_14"
            android:layout_width="80dip"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:background="@drawable/bg_yellow_selector"
            android:focusable="true"
            android:gravity="center"
            android:padding="10dip"
            android:text="@string/tv_down" />
    </RelativeLayout>

</RelativeLayout>

适配器

package com.example.appstoredemo.adapter;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.appstoredemo.R;
import com.example.appstoredemo.bean.AppBean;
import com.example.appstoredemo.download.DownloadInfo;
import com.example.appstoredemo.download.DownloadManager;
import com.example.appstoredemo.download.DownloadService;
import com.example.appstoredemo.utils.BitmapTools;
import com.example.appstoredemo.utils.Common;
import com.example.appstoredemo.utils.DownloadUtils;
import com.example.appstoredemo.utils.FileUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * @project AppStoreDemo
 * @ClassName AppRecommendAdapter.java
 * @Description 下载列表
 * @author xugang
 * @date 2015-8-16 下午4:16:43
 */
public class AppRecommendAdapter extends BaseAdapter {

    private List<AppBean> mList;
    private LayoutInflater mInflater;
    private BitmapTools mBitmapTools;
    private Context mContext;
    private DownloadManager downloadManager;

    public AppRecommendAdapter(Context context, List<AppBean> mList) {
        this.mList = mList;
        mInflater = LayoutInflater.from(context);
        mBitmapTools = new BitmapTools(context);
        this.mContext = context;
        downloadManager = DownloadService.getDownloadManager(context);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ViewHolder holder;
        if (null == view) {
            view = mInflater.inflate(R.layout.item_recommend, parent, false);
            holder = new ViewHolder(position);
            ViewUtils.inject(holder, view);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        holder.setRequest();
        holder.refresh();
        return view;
    }

    private class ViewHolder {
        @ViewInject(R.id.img_icon)
        private ImageView icon;
        @ViewInject(R.id.tv_size)
        private TextView size;
        @ViewInject(R.id.tv_title)
        private TextView title;
        @ViewInject(R.id.tv_company)
        private TextView company;
        @ViewInject(R.id.btn_down)
        private Button down;
        private AppBean appBean;

        private DownloadInfo downloadInfo;
        private DownloadUtils downloadUtils;

        public ViewHolder(int position) {
            appBean = mList.get(position);
            downloadUtils = new DownloadUtils(mContext, downloadManager, appBean);
        }
        //设置监听
        public void setRequest() {
            downloadInfo = downloadManager.getDownloadInfoByList(appBean.getApkUrl());
            if (downloadInfo != null) {
                HttpHandler<File> handler = downloadInfo.getHandler();
                if (handler != null) {
                    RequestCallBack callBack = handler.getRequestCallBack();
                    if (callBack instanceof DownloadManager.ManagerCallBack) {
                        DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
                        managerCallBack.setBaseCallBack(new DownloadRequestCallBack());
                    }
                    callBack.setUserTag(new WeakReference<ViewHolder>(this));
                }
            }
        }

        @OnClick(R.id.btn_down)
        public void start(View v) {
            downloadInfo = downloadManager.getDownloadInfoByList(appBean.getApkUrl());
            if (downloadInfo == null) {
                downloadUtils.downApp(new DownloadRequestCallBack());
                notifyDataSetChanged();
                return;
            }
            HttpHandler.State state = downloadInfo.getState();
            switch (state) {
            case WAITING:
                Toast.makeText(mContext, "排队中,请稍后~", Toast.LENGTH_SHORT).show();
                return;
            case STARTED:
            case LOADING:
                Toast.makeText(mContext, "正在下载,请稍后~", Toast.LENGTH_SHORT).show();
                break;
            case FAILURE:
            case CANCELLED:
                try {
                    downloadManager.resumeDownload(downloadInfo, new DownloadRequestCallBack());
                } catch (DbException e) {
                    LogUtils.e(e.getMessage(), e);
                }
                notifyDataSetChanged();
                break;
            case SUCCESS:
                if (Common.isAppInstall(mContext, downloadInfo.getPkg())) {
                    down.setText(R.string.tv_open);
                    Common.openApp(mContext, downloadInfo.getPkg());
                } else {
                    down.setText(R.string.tv_install);
                    if (FileUtils.exists(downloadInfo.getFileSavePath())) {
                        Common.installAPK(mContext, downloadInfo.getFileSavePath());
                    }
                }
                break;
            default:
                break;
            }
        }

        public void refresh() {
            mBitmapTools.disPlay(icon, appBean.getIcon());
            title.setText(appBean.getName());
            size.setText(appBean.getSize());
            company.setText(appBean.getCompany());
            if (Common.isAppInstall(mContext, appBean.getPkg())) {
                down.setText("打开");
                return;
            }
            if (downloadInfo == null) {
                down.setText("下载");
                return;
            }

            if (downloadInfo.getFileLength() > 0) {
                int progress = (int) (downloadInfo.getProgress() * 100 / downloadInfo.getFileLength());
                down.setText(progress + "%");
            } else {
                down.setText("0%");
            }

            HttpHandler.State state = downloadInfo.getState();

            switch (state) {
            case WAITING:
                down.setText("等待中...");
                break;
            case STARTED:
                down.setText("开始下载");
                break;
            case LOADING:
                break;
            case CANCELLED:
                down.setText("继续");
                break;
            case SUCCESS:
                down.setText("安装");
                break;
            case FAILURE:
                down.setText("重试");
                break;
            default:
                break;
            }
        }
    }

    private class DownloadRequestCallBack extends RequestCallBack<File> {
        private void refreshListItem() {
            if (userTag == null)
                return;
            WeakReference<ViewHolder> tag = (WeakReference<ViewHolder>) userTag;
            ViewHolder holder = (ViewHolder) tag.get();
            if (holder != null) {
                holder.refresh();
            }
        }

        @Override
        public void onStart() {
            refreshListItem();
        }

        @Override
        public void onLoading(long total, long current, boolean isUploading) {
            refreshListItem();
        }

        @Override
        public void onSuccess(ResponseInfo<File> responseInfo) {
            refreshListItem();
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            refreshListItem();
        }

        @Override
        public void onCancelled() {
            refreshListItem();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值