关闭

apk更新代码

标签: apk更新
57人阅读 评论(0) 收藏 举报
分类:

把项目中用到的apk更新代码记录一下,留待后面用:

public class UpdateManager {
    private static final String TAG = "Update";
    private  String str_url;
    private static final String UPDATE_SAVENAME = "My.apk";
    private String SAVEPATH = getSDPath()+"/my/";
    private Context mContext;
    private TextView tv_progress;


    private Dialog downloadDialog;
    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 String msg;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case DOWN_UPDATE:
                mProgress.setProgress(progress);
                tv_progress.setText(progress +"%");
                break;
            case DOWN_OVER:
                installApk();
                break;
            default:
                break;
            }
        };
    };

    public UpdateManager(Context context,String url,String mg) {
        this.mContext = context;
        //更改为绝对地址
        //this.str_url=urlIp+url;
        this.str_url=url;
        this.msg=mg;
    }



    public  void showDownloadDialog() {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("版本更新");
        builder.setMessage(msg);

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.download_progress, null);
        mProgress = (ProgressBar)v.findViewById(R.id.pb_download);
        tv_progress=(TextView) v.findViewById(R.id.tv_progress);
        builder.setView(v);
    /*  builder.setPositiveButton("正在下载...", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });*/
        downloadDialog = builder.create();
        downloadDialog.setCanceledOnTouchOutside(false);
        downloadDialog.show();
        downloadApk();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(str_url);
                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();
                }
                System.out.println("+++++file+++++++"+file.getPath());
                String apkFile = SAVEPATH + UPDATE_SAVENAME;
                File ApkFile = new File(apkFile);
                if (!file.exists()) {
                    file.mkdir();
                }
                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);
                        downloadDialog.dismiss();
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };


    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private void installApk() {
        File apkfile = new File(SAVEPATH + UPDATE_SAVENAME);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(intent);

    }

    public String getSDPath(){ 
        File sdDir = null; 
        boolean sdCardExist = Environment.getExternalStorageState() 
        .equals(android.os.Environment.MEDIA_MOUNTED); //判断sd卡是否存在 
        if (sdCardExist) 
        { 
        sdDir = Environment.getExternalStorageDirectory();//获取跟目录 
        } 
        return sdDir.toString(); 

        } 

}

下载对话框中进度条的xml

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

    <ProgressBar
        android:id="@+id/pb_download"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_gravity="center_vertical"
        android:layout_width="match_parent"
        android:layout_height="15dp"
        android:padding="3dp"
        android:max="100" />
    <TextView android:id="@+id/tv_progress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"/>

</LinearLayout>

apk更新一般用这两种方法进行通知:
1. 使用消息推送,可以使用集成好的SDK,比如极光推送SDK,后台推送更新消息,让用户在Notification中选择更新与否。
2. 在应用程序打开界面中访问服务器,获取当前最新apk版本,与本地应用程序versionCode进行比较。

private void getVersionInfo() {
    PackageManager packageManager = getPackageManager();
    PackageInfo packageInfo;
    try {
        packageInfo = packageManager.getPackageInfo(getPackageName(),
                PackageManager.GET_ACTIVITIES);
        VERSION_CODE = packageInfo.versionCode;
        VERSION_NAME = packageInfo.versionName;
    } catch (NameNotFoundException e) {
    }

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:17233次
    • 积分:456
    • 等级:
    • 排名:千里之外
    • 原创:25篇
    • 转载:14篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论