android 更新下載apk並且安裝


package com.zq.ydsp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.zq.ydsp.utils.LogUtil;
//import android.content.DialogInterface;
//import android.content.DialogInterface.OnClickListener;

public class UpdateManager {
    /**
     * 版本更新
     */
    private Context mContext;
    // 返回的安裝包url
    // private String apkUrl =
    // "http://192.168.1.117:8008/webservices/Json.aspx?mod=api&act=getDownload&meth=load&strName=fdzw.apk";
    private String apkUrl;
    private Dialog noticeDialog;
    private Dialog downloadDialog;
    /* 下載包安裝路徑 */
    private static final String savePath = "/sdcard/移動審批/";
    private static final String saveFileName = savePath + "移動審批.apk";
    private TextView tv;
    /* 進度條與通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private int progress;
    private Thread downLoadThread;
    private boolean interceptFlag = false;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWN_UPDATE:
                tv.setText(progress + "%");
                mProgress.setProgress(progress);
//                popup_tv.setText(progress + "%");
//                popup_progress.setProgress(progress);
                if (progress == 99) {
                    downloadDialog.dismiss();
//                    popWindow.dismiss();
                }
                break;
            case DOWN_OVER:
                installApk();
                break;
            default:
                break;
            }
        };
    };

    public UpdateManager(Context context) {
        this.mContext = context;
        view = new View(mContext);
    }

    // 外部接口讓主Activity調用
    public void checkUpdateInfo(String str, String apkUrl) {
        this.apkUrl = apkUrl;
        showNoticeDialog(str);
        
//        showPopWindow_jcgx(mContext, view, str);
    }
    
    private View view;
    private PopupWindow popWindow;
    private LinearLayout popup_no, popup_yes;
    private TextView popup_gx;
    private TextView popup_tv;
    private ProgressBar popup_progress;
    private LinearLayout popup_qx;
    
    private void showPopWindow_jcgx(Context context, View parent, String str) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View vPopWindow = inflater.inflate(R.layout.popup_jcgx, null, false);
        // 寬300 高300
        popWindow = new PopupWindow(vPopWindow, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);

        popup_gx = (TextView) vPopWindow.findViewById(R.id.popup_gx);
        popup_no = (LinearLayout) vPopWindow.findViewById(R.id.popup_no);
        popup_yes = (LinearLayout) vPopWindow.findViewById(R.id.popup_yes);
        
        popup_gx.setText(str);
        
        popup_no.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
            }
        });
        popup_yes.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
                showPopWindow_gx(mContext, view);
            }
        });

        popWindow.dismiss(); // Close the Pop Window
        popWindow.setOutsideTouchable(true);
        popWindow.setFocusable(true);

        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }
    
    private void showPopWindow_gx(Context context, View parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View vPopWindow = inflater.inflate(R.layout.popup_progress, null, false);
        // 寬300 高300
        popWindow = new PopupWindow(vPopWindow, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, true);

        popup_tv = (TextView) vPopWindow.findViewById(R.id.popup_tv);
        popup_progress = (ProgressBar) vPopWindow.findViewById(R.id.popup_progress);
        popup_qx = (LinearLayout) vPopWindow.findViewById(R.id.popup_qx);
        
        popup_qx.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                popWindow.dismiss();
                interceptFlag = true;
            }
        });
        
        downloadApk();

        popWindow.dismiss(); // Close the Pop Window
        popWindow.setOutsideTouchable(true);
        popWindow.setFocusable(true);

        popWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    private void showNoticeDialog(String str) {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("移動審批");
        builder.setMessage(str);
        builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("暫不更新",new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog() {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("移動審批");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progress, null);
        tv = (TextView) v.findViewById(R.id.tv);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);

        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();

        downloadApk();
    }
 private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);

                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新進度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下載完成通知安裝
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 點擊取消就停止下載.
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 下載apk
     * 
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安裝apk
     * 
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);// 顯示用戶數據
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

}

布局文件

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="正在下載"
            android:textColor="#000000"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:textColor="#000000"
            android:textSize="15sp" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
         />

</LinearLayout>

 


免責聲明!

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



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