android版本更新

package com.hroot.www.utils;

import android.app.Dialog;
import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.RemoteViews;

import com.hroot.www.application.HrMarketApplication;
import com.hroot.www.bean.UpDataBean;
import com.hroot.www.common.utils.AppHttpUrl;
import com.hroot.www.hrmarket.R;
import com.hroot.www.views.AlertDialog;
import com.hroot.www.views.MyToast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.EOFException;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/7/6.
 */
public class CheckVersionTask implements Runnable {

    private InputStream is;
    private UpDataBean bean;
    private final  int UPDATA_NONEED = 1;
    private final  int UPDATA_CLIENT = 2;
    private final  int GET_UNDATAINFO_ERROR =3;
    private final  int  DOWN_ERROR=4;
    private long mTaskid;//下载任务ID
    private DownloadManager downloadManager;//下载管理器
    private String fileName = "hrMarket.apk";//文件名
    private boolean flag = false;
    private Context mContext;
    //文件路径
    private String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()+ File.separator+fileName;

    public CheckVersionTask(Context mContext,boolean flag){
        this.mContext = mContext;
        this.flag = flag;
    }

    @Override
    public void run() {
       try {

           String path = AppHttpUrl.UPDATA_VER_XML;
           URL url = new URL(path);
           HttpURLConnection conn = (HttpURLConnection) url
                   .openConnection();
           conn.setConnectTimeout(5000);
           conn.setRequestMethod("GET");
           int responseCode = conn.getResponseCode();
           if (responseCode == 200) {
               // 从服务器获得一个输入流
               is = conn.getInputStream();
           }
           bean = UpdataInfoParser.getUpdataInfo(is);
           if (compare(bean.getVersion(),getVersionName())) {
               Message msg = new Message();
               msg.what = UPDATA_CLIENT;
               handler.sendMessage(msg);

           } else {
               Message msg = new Message();
               msg.what = UPDATA_NONEED;
               handler.sendMessage(msg);

           }
       }catch (Exception e) {
           Message msg = new Message();
           msg.what = GET_UNDATAINFO_ERROR;
           handler.sendMessage(msg);
           e.printStackTrace();
       }

    }

    private String getVersionName() throws Exception {
        //getPackageName()是你当前类的包名,0代表是获取版本信息
        PackageManager packageManager = mContext.getPackageManager();
        PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(),
                0);
        return packInfo.versionName;
    }
    private boolean compare(String serviceVer,String loclhostVer){
        try {
            String s =serviceVer.replace(".","");
            String ss = loclhostVer.replace(".","");
            int serCode = Integer.parseInt(s);
            int locaCode = Integer.parseInt(ss);
            if(serCode>locaCode){
                return true;
            }
        }catch (Exception e){
            return false;
        }
        return  false;
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            HrMarketApplication.getApplication().dissDialogProgress();
            switch (msg.what) {
                case UPDATA_NONEED:
                    if(flag){
                        MyToast.make("已经是最新版本了",0,mContext).show();
                    }
                    break;
                case UPDATA_CLIENT:
                    //对话框通知用户升级程序
                    showDialog();
                    break;
                case GET_UNDATAINFO_ERROR:
                    if(flag){
                        MyToast.make("请求超时",0,mContext).show();
                    }
                    break;
                case DOWN_ERROR:
                    //下载apk失败
                    MyToast.make("下载失败",0,mContext).show();
                    break;
            }
        }
    };


    public void showDialog(){
        new AlertDialog(AppManager.getAppManager().currentActivity()).builder()
                .setMsg(bean.getDescription())
                .setTitle("提示")
                .setCancelable(false)
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("更新", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        downloadApk("http://gdown.baidu.com/data/wisegame/2eeee3831c9dbc42/QQ_374.apk");
                        connectDownLoad();
                    }

                }).show();
    }


    /**
     * 根据XUtils下载文件带状态栏下载APK
     */
    private void connectDownLoad(){
        mNotificationManager = (NotificationManager) mContext.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        HttpUtils http = new HttpUtils();
        http.configTimeout(30000);
        http.configSoTimeout(30000);
        http.download("http://gdown.baidu.com/data/wisegame/2eeee3831c9dbc42/QQ_374.apk", filePath, false, false, new RequestCallBack<File>() {
            @Override
            public void onStart() {
                super.onStart();
                setUpNotification("s",mContext);
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                super.onLoading(total, current, isUploading);
                int progress = (int) (current * 100/total);
                RemoteViews contentview = mNotification.contentView;
                contentview.setTextViewText(R.id.tv_progress, progress + "%");
                contentview.setProgressBar(R.id.progressbar, 100, progress, false);
                mNotificationManager.notify(NOTIFY_ID, mNotification);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                mNotificationManager.cancel(NOTIFY_ID);
                installApk(new File(filePath));
            }

            @Override
            public void onFailure(HttpException e, String s) {
                RemoteViews contentview = mNotification.contentView;
                contentview.setTextViewText(R.id.tv_progress,"下载失败");
                contentview.setProgressBar(R.id.progressbar, 100,0, false);
                mNotificationManager.notify(NOTIFY_ID, mNotification);
            }
        });
    }
    private static final int NOTIFY_ID = 0;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private void setUpNotification(String packageName,Context context) {
        mNotification = new Notification(R.drawable.ssdk_oks_classic_qq, "正在下载",  System.currentTimeMillis());
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.download_notification_layout);
        mNotification.contentView = contentView;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }


    /**
     * 系统自带DownloadManager下载APK
     * @param url
     */
    private void downloadApk(String url){
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedOverRoaming(false);//漫游是否下载

        //设置文件类型,可以在下载结束后自动打开文件
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        request.setMimeType(mimeString);


        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setVisibleInDownloadsUi(true);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,filePath);

        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        mTaskid = downloadManager.enqueue(request);
        HrMarketApplication.getApplication().registerReceiver(receiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();
        }
    };

    /**
     * 检查下载状态
     */
    private void checkDownloadStatus(){
        DownloadManager.Query query =  new DownloadManager.Query();
        query.setFilterById(mTaskid);
        Cursor c =downloadManager.query(query);
        if(c.moveToFirst()){
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status){
                case DownloadManager.STATUS_PAUSED://下载暂停
                    break;
                case DownloadManager.STATUS_PENDING://下载延迟
                    break;
                case DownloadManager.STATUS_RUNNING://正在下载
                    break;
                case DownloadManager.STATUS_SUCCESSFUL://下载完成
                    installApk(new File(filePath));
                    break;
                case DownloadManager.STATUS_FAILED://下载失败
                    Message msg = new Message();
                    msg.what = DOWN_ERROR;
                    handler.sendMessage(msg);
                    break;
            }
        }
    }

    /**
     * 安装APK
     * @param file
     */
    private void installApk(File file){
        if(!file.exists()){
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri =Uri.parse("file://"+file.toString());
        intent.setDataAndType(uri,"application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

}

package com.hroot.www.utils;

import android.util.Xml;

import com.hroot.www.bean.UpDataBean;

import org.xmlpull.v1.XmlPullParser;

import java.io.InputStream;

/**
 * Created by Administrator on 2016/7/6.
 */
public class UpdataInfoParser {
    public static UpDataBean getUpdataInfo(InputStream is) throws Exception{
        XmlPullParser parser = Xml.newPullParser();
        parser.setInput(is, "utf-8");
        int type = parser.getEventType();
        UpDataBean info = new UpDataBean();
        while(type != XmlPullParser.END_DOCUMENT ){
            switch (type) {
                case XmlPullParser.START_TAG:
                    if("version".equals(parser.getName())){
                        info.setVersion(parser.nextText());
                    }else if ("url".equals(parser.getName())){
                        info.setUrl(parser.nextText());
                    }else if ("description".equals(parser.getName())){
                        info.setDescription(parser.nextText());
                    }
                    break;
            }
            type = parser.next();
        }
        return info;
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:orientation="horizontal" >

            <ImageView
                android:id="@+id/image"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:scaleType="centerCrop"
                android:layout_gravity="center_vertical"
                android:src="@mipmap/app" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="3dp"
                android:orientation="vertical" >
                 <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:id="@+id/name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:text="河马网"
                         />

                    <TextView
                        android:id="@+id/tv_progress"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_vertical"
                        android:layout_alignParentRight="true"
                        android:gravity="center"
                        android:minWidth="60dp"
                         />
                </RelativeLayout>

                <ProgressBar
                    android:id="@+id/progressbar"
                    style="?android:attr/progressBarStyleHorizontal"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:max="100"
                    android:progress="0"
                    />
            </RelativeLayout>
        </LinearLayout>


</RelativeLayout>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值