com.gdpi.app.UpdateManager.java Source code

Java tutorial

Introduction

Here is the source code for com.gdpi.app.UpdateManager.java

Source

package com.gdpi.app;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import model.URLs;
import ui.MainFragment;
import utils.AlertUtils;
import utils.HttpMultipartPost;
import view.NumberProgressBar;

import static android.os.Build.VERSION_CODES.N;

/**
 * * Copyright (C) 2010 The Android Open Source Project
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License. --------------------------------------- PLEASE READ
 * --------------------------------------- CopyRight (c) ?? ??
 * ??GDTEC_Spot ??UpdateManager ??  huangchunfei
 * Administrator 20131024 ?4:35:42 20131024 ?4:35:42
 */
public class UpdateManager {

    private MyApp app = MyApp.getInstance();
    private static final int CHECKE_UPDATE = 0;
    /*  */
    private static final int DOWNLOAD_UPDATE = 1;
    /* ? */
    private static final int DOWNLOAD_FINISH = 2;
    private static final int DOWN_ERR = 3;

    private static final int GET_UPDATE_URL = 4;
    /* ? */
    private String mSavePath;
    /* ?? */
    private int progress;
    /* ?? */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* ? */
    private NumberProgressBar mProgress;
    private Dialog mDownloadDialog;

    private String Url;
    private String Version;
    private String name;
    private String updateinfo;

    private Dialog noticeDialog;
    @SuppressWarnings("unused")
    private String apkFileSize;
    @SuppressWarnings("unused")
    private String tmpFileSize;
    private long time = 0;
    private boolean p = false;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
            case GET_UPDATE_URL:
                if (loading != null) {
                    loading.dismiss();
                    loading = null;
                }
                if (msg.obj != null) {
                    try {
                        JSONObject j = new JSONObject((String) msg.obj);
                        if ("1".equals(j.optString("Code"))) {
                            String data = j.optString("Data");
                            JSONObject d = new JSONObject(data);
                            updateinfo = d.optString("AndroidUpdateContent");
                            if (!TextUtils.isEmpty(d.optString("APKPath"))) {
                                Url = URLs.URL_BASE_APP + d.optString("APKPath");
                                showNoticeDialog();
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHECKE_UPDATE:
                if (msg.obj != null) {
                    try {
                        JSONObject j = new JSONObject((String) msg.obj);
                        if ("1".equals(j.optString("Code"))) {
                            String data = j.optString("Data");
                            JSONObject d = new JSONObject(data);
                            Version = d.optString("AndroidVersion");
                            app.setProps("version", Version);
                            boolean isUpdate = isUpdate(Version);
                            if (isUpdate) {
                                getUpdateUrl();
                            } else if (p) {
                                if (loading != null) {
                                    loading.dismiss();
                                    loading = null;
                                }
                                Toast.makeText(mContext, "?", Toast.LENGTH_SHORT).show();
                            }

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            // 
            case DOWNLOAD_UPDATE:
                if ((System.currentTimeMillis() - time) > 100) {
                    // ??
                    mProgress.setProgress(progress);
                    time = System.currentTimeMillis();
                }

                break;
            case DOWNLOAD_FINISH:
                // 
                if (mDownloadDialog != null) {
                    mDownloadDialog.dismiss();
                }
                installApk();

                break;
            case DOWN_ERR:
                if (mDownloadDialog != null) {
                    mDownloadDialog.dismiss();
                    Toast.makeText(mContext, "??", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
            }
        }

    };

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

    private Dialog loading;

    public void checkUpdate(boolean b) {
        try {
            p = b;
            if (b) {
                loading = AlertUtils.showLoading(mContext);
                loading.show();
            }
            Map<String, String> paras = new HashMap<>();
            paras.put("enterprise", URLs.ENTERPRISE);
            HttpMultipartPost httpMultipartPost = new HttpMultipartPost(mContext, URLs.URL_UPDATE, paras, false);
            httpMultipartPost.setCallback(new HttpMultipartPost.HttpConnectionCallback() {

                @Override
                public void result(String result) {

                    Message message = new Message();
                    message.what = CHECKE_UPDATE;
                    message.obj = result;
                    mHandler.sendMessage(message);
                }

                @Override
                public void progressUpdate(Integer... progress) {

                }
            });
            httpMultipartPost.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getUpdateUrl() {
        try {
            Map<String, String> paras = new HashMap<>();
            paras.put("enterprise", URLs.ENTERPRISE);
            HttpMultipartPost httpMultipartPost = new HttpMultipartPost(mContext, URLs.URL_UPDATE_CLIENT, paras,
                    false);
            httpMultipartPost.setCallback(new HttpMultipartPost.HttpConnectionCallback() {

                @Override
                public void result(String result) {
                    Message message = new Message();
                    message.what = GET_UPDATE_URL;
                    message.obj = result;
                    mHandler.sendMessage(message);
                }

                @Override
                public void progressUpdate(Integer... progress) {

                }
            });
            httpMultipartPost.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ?
     *
     * @return
     */
    public boolean isUpdate(String version_new) {

        // ??
        int versionCode = getVersionCode(mContext);
        if (null != version_new) {
            try {
                int serviceCode = Integer.parseInt(version_new);
                // 
                if (serviceCode > versionCode) {
                    app.setNeedToUpdate(true);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * ??
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // ??AndroidManifest.xmlandroid:versionCode
            versionCode = context.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * ?
     */
    @SuppressLint("InflateParams")
    private void showDownloadDialog() {

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.update, null);
        mProgress = (NumberProgressBar) v.findViewById(R.id.update_progress);
        mDownloadDialog = AlertUtils.showAlertBtn(mContext, v, "", "?", null,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if (mDownloadDialog != null) {
                            mDownloadDialog.dismiss();
                            mDownloadDialog = null;
                        }
                        cancelUpdate = true;
                    }
                }, null);
        mDownloadDialog.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
                cancelUpdate = true;
            }
        });
        downloadApk();
    }

    /**
     * Notification?
     */
    public NotificationManager mNotificationManager;
    private Notification nitify;

    /**
     * ??
     */
    @SuppressWarnings({ "deprecation", "unused" })
    private void showNotify() {
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

        int icon = R.drawable.icon;
        CharSequence tickerText = "";
        long when = System.currentTimeMillis();
        nitify = new Notification(icon, tickerText, when);

        // "?"?
        nitify.flags = Notification.FLAG_ONGOING_EVENT;
        RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.view_custom_progress);
        contentView.setTextViewText(R.id.tv_custom_progress_title, name);
        // 
        nitify.contentView = contentView;
        Intent intent = new Intent(mContext, MainFragment.class);
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
        // ?
        nitify.contentIntent = contentIntent;
        mNotificationManager.notify(notifyId, nitify);
    }

    /**
     * Nitify
     */
    @SuppressWarnings({ "unused", "deprecation" })
    @TargetApi(16)
    private void closeNitify() {
        nitify.flags = Notification.FLAG_AUTO_CANCEL;
        nitify.contentView = null;
        Intent intent = new Intent(mContext, MainFragment.class);
        // ?
        intent.putExtra("completed", "yes");
        // ?,?flags?FLAG_UPDATE_CURRENT
        PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        nitify = new Notification.Builder(mContext).setAutoCancel(true).setContentTitle("?")
                .setContentText("").setContentIntent(contentIntent)
                .setSmallIcon(R.drawable.icon).setWhen(System.currentTimeMillis()).build();
        mNotificationManager.notify(notifyId, nitify);

    }

    /**
     * NotificationID
     */
    int notifyId = 102;

    /**
     * apk
     */
    private void downloadApk() {
        // ?
        // showNotify();
        new downloadApkThread().start();
    }

    /**
     * 
     *
     * @author gdtec
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {

        @Override
        public void run() {
            try {
                String storageState = Environment.getExternalStorageState();
                if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                    mSavePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GPDI/";
                    File savedir = new File(mSavePath);
                    if (!savedir.exists()) {
                        savedir.mkdirs();
                    }
                }
                name = "gpdi_" + Version + ".apk";
                Log.i("TAG", "run: " + Url);
                URL url = new URL(Url);
                // 
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                // ??
                int length = conn.getContentLength();
                // ?
                InputStream is = conn.getInputStream();
                // ??2?
                DecimalFormat df = new DecimalFormat("0.00");
                // ???
                apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

                File apkFile = new File(mSavePath, name);

                FileOutputStream fos = new FileOutputStream(apkFile);
                int count = 0;
                // 
                byte buf[] = new byte[1024];
                // 
                do {
                    int numread = is.read(buf);
                    count += numread;

                    // ????
                    tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
                    // ??
                    progress = (int) (((float) count / length) * 100);
                    // 
                    mHandler.sendEmptyMessage(DOWNLOAD_UPDATE);
                    if (numread <= 0) {
                        // ?
                        mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                        break;
                    }
                    // 
                    fos.write(buf, 0, numread);
                } while (!cancelUpdate);// ??.
                fos.close();
                is.close();
            } catch (Exception e) {
                mHandler.sendEmptyMessage(DOWN_ERR);
                e.printStackTrace();
            }
        }
    }

    /**
     * APK
     */
    private void installApk() {
        /**
         * android7.0
         */
        File apkfile = new File(mSavePath, name);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // Activity?Activity,?
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= N) { //?7.0
            //?1 , ?2 Provider? ???   ?3  
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.gpdi.app.fileprovider", apkfile);
            //??Uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());

    }

    /**
     * ?
     */
    private void showNoticeDialog() {

        updateinfo = updateinfo.replaceAll("#", "<br/>");
        final TextView text = new TextView(mContext);//
        text.setGravity(Gravity.LEFT | Gravity.CENTER);
        text.setTextSize(16);
        text.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (noticeDialog != null) {
                    noticeDialog.dismiss();
                    noticeDialog = null;
                }
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(Url));

                mContext.startActivity(intent);
            }
        });
        text.setText(Html.fromHtml("<a href=" + Url + ">" + updateinfo + "</a>"));
        noticeDialog = AlertUtils.showAlertBtn(mContext, text, "APP???", "?", "??",
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        showDownloadDialog();
                        noticeDialog.dismiss();
                        noticeDialog = null;
                    }
                }, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        noticeDialog.dismiss();
                        noticeDialog = null;
                    }
                });
    }

}