Android App在线更新的代码

转载 2016年08月30日 16:13:22
import java.io.File;   
import java.io.FileOutputStream;   
import java.io.InputStream;   
import java.net.URL;   
import java.net.URLConnection;   
import android.app.Activity;   
import android.app.AlertDialog;   
import android.app.ProgressDialog;   
import android.content.Context;   
import android.content.DialogInterface;   
import android.content.Intent;   
import android.content.pm.PackageInfo;   
import android.content.pm.PackageManager.NameNotFoundException;   
import android.net.ConnectivityManager;   
import android.net.NetworkInfo;   
import android.net.Uri;   
import android.util.Log;   
import android.webkit.URLUtil;   
import com.hiyo.game.pdk.activity.R;   
/**  
 * Android AutoUpdate.  
 *   
 * lazybone/2010.08.20  
 *   
 * 1.Set apkUrl.  
 *   
 * 2.check().  
 *   
 * 3.add delFile() method in resume()\onPause().  
 */  
public class MyAutoUpdate {   
    public Activity activity = null;   
    public int versionCode = 0;   
    public String versionName = "";   
    private static final String TAG = "AutoUpdate";   
    private String currentFilePath = "";   
    private String currentTempFilePath = "";   
    private String fileEx = "";   
    private String fileNa = "";   
    private String strURL = "http://127.0.0.1:81/ApiDemos.apk";   
    private ProgressDialog dialog;   
    public MyAutoUpdate(Activity activity) {   
        this.activity = activity;   
        getCurrentVersion();   
    }   
    public void check() {   
        if (isNetworkAvailable(this.activity) == false) {   
            return;   
        }   
        if (true) {// Check version.   
            showUpdateDialog();   
        }   
    }   
    public static boolean isNetworkAvailable(Context ctx) {   
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);   
            NetworkInfo info = cm.getActiveNetworkInfo();   
            return (info != null && info.isConnected());   
        } catch (Exception e) {   
            e.printStackTrace();   
            return false;   
        }   
    }   
    public void showUpdateDialog() {   
        @SuppressWarnings("unused")   
        AlertDialog alert = new AlertDialog.Builder(this.activity)   
                .setTitle("Title")   
                .setIcon(R.drawable.icon)   
                .setMessage("Update or not?")   
                .setPositiveButton("Update",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                downloadTheFile(strURL);   
                                showWaitDialog();   
                            }   
                        })   
                .setNegativeButton("Cancel",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                dialog.cancel();   
                            }   
                        }).show();   
    }   
    public void showWaitDialog() {   
        dialog = new ProgressDialog(activity);   
        dialog.setMessage("Waitting for update...");   
        dialog.setIndeterminate(true);   
        dialog.setCancelable(true);   
        dialog.show();   
    }   
    public void getCurrentVersion() {   
        try {   
            PackageInfo info = activity.getPackageManager().getPackageInfo(   
                    activity.getPackageName(), 0);   
            this.versionCode = info.versionCode;   
            this.versionName = info.versionName;   
        } catch (NameNotFoundException e) {   
            e.printStackTrace();   
        }   
    }   
    private void downloadTheFile(final String strPath) {   
        fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())   
                .toLowerCase();   
        fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,   
                strURL.lastIndexOf("."));   
        try {   
            if (strPath.equals(currentFilePath)) {   
                doDownloadTheFile(strPath);   
            }   
            currentFilePath = strPath;   
            Runnable r = new Runnable() {   
                public void run() {   
                    try {   
                        doDownloadTheFile(strPath);   
                    } catch (Exception e) {   
                        Log.e(TAG, e.getMessage(), e);   
                    }   
                }   
            };   
            new Thread(r).start();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
    private void doDownloadTheFile(String strPath) throws Exception {   
        Log.i(TAG, "getDataSource()");   
        if (!URLUtil.isNetworkUrl(strPath)) {   
            Log.i(TAG, "getDataSource() It's a wrong URL!");   
        } else {   
            URL myURL = new URL(strPath);   
            URLConnection conn = myURL.openConnection();   
            conn.connect();   
            InputStream is = conn.getInputStream();   
            if (is == null) {   
                throw new RuntimeException("stream is null");   
            }   
            File myTempFile = File.createTempFile(fileNa, "." + fileEx);   
            currentTempFilePath = myTempFile.getAbsolutePath();   
            FileOutputStream fos = new FileOutputStream(myTempFile);   
            byte buf[] = new byte[128];   
            do {   
                int numread = is.read(buf);   
                if (numread <= 0) {   
                    break;   
                }   
                fos.write(buf, 0, numread);   
            } while (true);   
            Log.i(TAG, "getDataSource() Download  ok...");   
            dialog.cancel();   
            dialog.dismiss();   
            openFile(myTempFile);   
            try {   
                is.close();   
            } catch (Exception ex) {   
                Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);   
            }   
        }   
    }   
    private void openFile(File f) {   
        Intent intent = new Intent();   
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
        intent.setAction(android.content.Intent.ACTION_VIEW);   
        String type = getMIMEType(f);   
        intent.setDataAndType(Uri.fromFile(f), type);   
        activity.startActivity(intent);   
    }   
    public void delFile() {   
        Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");   
        File myFile = new File(currentTempFilePath);   
        if (myFile.exists()) {   
            myFile.delete();   
        }   
    }   
    private String getMIMEType(File f) {   
        String type = "";   
        String fName = f.getName();   
        String end = fName   
                .substring(fName.lastIndexOf(".") + 1, fName.length())   
                .toLowerCase();   
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")   
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {   
            type = "audio";   
        } else if (end.equals("3gp") || end.equals("mp4")) {   
            type = "video";   
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")   
                || end.equals("jpeg") || end.equals("bmp")) {   
            type = "image";   
        } else if (end.equals("apk")) {   
            type = "application/vnd.android.package-archive";   
        } else {   
            type = "*";   
        }   
        if (end.equals("apk")) {   
        } else {   
            type += "/*";   
        }   
        return type;   
    }   
}  

Android进阶之APP在线更新

在线更新要分为几大块 :在线检测 在线下载 离线安装。 安装完了重启应用(因为有些APP是安装在系统目录下的)先看下入口MainActivity的代码 里面也就设置了个自定义view。public ...

Android实现APP在线下载更新

前言 项目地址:https://github.com/teprinciple/UpdateAppDemo 现在的android应用app会隔一段时间发布一个新的版本,当你打开某个app,如果有最新...

android 反纠结app开发: 在线程中更新view

通过Handler更新UI实例: 步骤: 1、创建Handler对象(此处创建于主线程中便于更新UI)。 2、构建Runnable对象,在Runnable中更新界面。 3、在子线程的run方法中向UI...

Android 在线下载更新App 下载完成安装APK(兼容Android7.0)

首先对android7.0的打开文件方式进行适配 使用FileProvider 第一步: 在AndroidManifest.xml清单文件中注册provider,因为provider也是Andro...

Android App更新版本以及提示用户下载最新apk(有图,有代码,有最终效果图)详细解释及思路

android应用的版本更新,以及推送提示用户最新版本下载代码与逻辑: 作为一名Android软件开发的程序员,这个功能是必须要掌握的,因为这个功能不管你是什么app都会用到,除非你这个项目废弃了,因...

Android APP 版本更新通知代码

public class UpdateNotification { private static HashMap getLatestVersionData(String paramString) ...

android app在线自动升级(一)

android app在线自动升级(一)
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android App在线更新的代码
举报原因:
原因补充:

(最多只允许输入30个字)