1. 程式人生 > >android APK升級

android APK升級

1.獲取版本號
2.對比版本號
3.下載apk檔案
4.啟動安裝
/**
 * 升級
 *
 * @param view
*/
public void onUpgrade(View view) {
    if (isUpgrade) {
        return;
}
    isUpgrade = true;
mUpdateAPKThread = new UpdateAPKThread(this, "url");
    new UpgradeThread().start();

}

class UpgradeThread extends Thread {
    @Override
public void 
run() { super.run(); boolean flag = mUpdateAPKThread.checkIsNeedUpdate(); Message msg = Message.obtain(); msg.what = KEY_UPGRADE; Bundle bundle = new Bundle(); bundle.putBoolean("upgrade", flag); msg.setData(bundle); handler.sendMessage(msg); } }
case KEY_UPGRADE:
    if (msg.getData().getBoolean("upgrade"
)) { String message = mUpdateAPKThread.getDetail(); new AlertDialog.Builder(LoginActivity.this) .setCancelable(false) .setTitle(getString(R.string.upgrade)) .setMessage(message) .setPositiveButton(getString(R.string.confirm
), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mProgressDialog = new MyProgressDialog(LoginActivity.this, getString(R.string.load), false); mUpdateAPKThread.startDownloadThread(); isUpgrade = false; } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { isUpgrade = false; } }).create().show(); } else { Yancy.warning(LoginActivity.this, getString(R.string.version)).show(); isUpgrade = false; } break;
/**
 * 檔案長度
 */
private int max = 0;
@Override
public void setMax(int length) {
    max = length;
}

@Override
public void setProgresss(int len) {
    mProgressDialog.setProgress(len * 100 / max);
}

@Override
public void onSuccess() {
    mUpdateAPKThread.installApk();
mProgressDialog.dismiss();
}

@Override
public void onFail() {
    Yancy.error(this, getString(R.string.download_failed)).show();
mProgressDialog.dismiss();
}

package com.yancy.sdk.upgrade;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import com.yancy.sdk.app.App;
import com.yancy.sdk.utils.AppUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
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;
/**
 * create by dpc on 2017-5-10
 */
public class UpdateAPKThread {

    private Context mContext;
    private String strURL;
    private File downloadFile;
    private DownloadListener downloadListener;
    private String detail;
    private String varUrl;
    private String apkName;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    downloadListener.setMax((int) msg.obj);
                    break;
                case 1:
                    downloadListener.setProgresss((int) msg.obj);
                    break;
                case 2:
                    downloadListener.onSuccess();
                    break;
                case 3:
                    downloadListener.onFail();
                    break;
                default:
                    break;
}
        }
    };
    public UpdateAPKThread(Context mContext, String strURL) {
        this.mContext = mContext;
        this.strURL = strURL;
setDownloadListener((DownloadListener) mContext);
}

    public void setDownloadListener(DownloadListener downloadListener) {
        this.downloadListener = downloadListener;
}

    public interface DownloadListener {
        /**
         * 設定檔案長度
         *
         * @param length
*/
void setMax(int length);
/**
         * 進度
         *
         * @param len
*/
void setProgresss(int len);
/**
         * 成功
         */
void onSuccess();
/**
         * 失敗
         */
void onFail();
}

    /**
     * 是否需要更新
     *
     * @return
*/
public boolean checkIsNeedUpdate() {
        if (strURL.equals("")) {
            return false;
}
        String data = getJsonContent(strURL);
        if (data.equals("")) {
            return false;
}
        return parseJson(mContext, data);
}


    private boolean parseJson(Context context, String strResult) {
        try {
            JSONObject jsonObject = new JSONObject(strResult);
String verName = jsonObject.getString("verName");
String verCode = jsonObject.getString("verCode");
varUrl = jsonObject.getString("varUrl");
detail = jsonObject.getString("detail");
apkName = jsonObject.getString("apkname");
            int code = Integer.parseInt(verCode);
            if (code > AppUtils.getVersionCode(context)) {
                return true;
}
        } catch (JSONException e) {
            e.printStackTrace();
} catch (NumberFormatException e) {
            e.printStackTrace();
}
        return false;
}

    private String getJsonContent(String urlStr) {
        try {
            URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
                    .openConnection();
// 設定連線屬性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
            if (200 == httpConn.getResponseCode()) {
                return ConvertStream2Json(httpConn.getInputStream());
}
        } catch (MalformedURLException e) {
            e.printStackTrace();
} catch (IOException e) {
            e.printStackTrace();
}
        return "";
}

    private String ConvertStream2Json(InputStream inputStream) {
        String jsonStr = "";
ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, len);
}
            jsonStr = new String(out.toByteArray());
} catch (IOException e) {
            e.printStackTrace();
}
        return jsonStr;
}

    public String getDetail() {
        return detail;
}

    Thread mThread;
    boolean isDownloading = false;
    public void startDownloadThread() {
        final String urlStr = varUrl;
        final String fileName = apkName;
mThread = new Thread() {
            public void run() {
                isDownloading = true;
                try {
                    URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
// 獲得檔案的長度
int contentLength = conn.getContentLength();
mHandler.obtainMessage(0, contentLength).sendToTarget();
File filePath = new File(Environment.getExternalStorageDirectory() + "/apk/");
                    if (!filePath.exists()) {
                        filePath.mkdirs();
filePath = new File(Environment.getExternalStorageDirectory() + "/apk/" + "/.test.txt");
                        if (!filePath.exists())
                            try {
                                filePath.createNewFile();
} catch (IOException e) {
                                e.printStackTrace();
}
                        FileNotification.updateNotify(filePath);
}

                    String pathName = Environment.getExternalStorageDirectory() + "/apk/" + fileName;
downloadFile = new File(pathName);
InputStream input = conn.getInputStream();
                    if (downloadFile.exists()) {
                        downloadFile.delete();
}
                    downloadFile.createNewFile();
FileOutputStream output = new FileOutputStream(downloadFile);
                    byte[] buffer = new byte[1024];
                    int len; // 重要引數
int sum = 0;
                    while ((len = input.read(buffer)) != -1 && isDownloading) {
                        sum += len;
mHandler.obtainMessage(1, sum).sendToTarget();
output.write(buffer, 0, len);
Thread.sleep(1);
}
                    output.close();
input.close();
mHandler.obtainMessage(2).sendToTarget();
} catch (IOException e1) {
                    mHandler.obtainMessage(3).sendToTarget();
e1.printStackTrace();
} catch (InterruptedException e) {
                    e.printStackTrace();
}
            }
        };
mThread.start();
}

    /**
     * 安裝APK檔案
     */
public void installApk() {
        if (downloadFile != null && !downloadFile.exists()) {
            return;
}
        Intent i = new Intent(Intent.ACTION_VIEW);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setDataAndType(Uri.parse("file://" + downloadFile.toString()),
"application/vnd.android.package-archive");
mContext.startActivity(i);
}
}