工具类之app强制下载更新

public class DownloadElement extends Thread {
    private static final int IS_DOWNLOADING = 1;//正在下载
    private static final int DOWNLOAD_CANCEL = 3;//取消下载
    public static final int DOWNLOAD_FINISH = 5; //完成下载
    private static final int DOWNLOAD_ERROR = 7; //下载错误
    private String fileName = "app.apk";
    private Activity activity;
    private String updateUrl;// 更新地址
    private String apkFile;// apk下载的路径
    private MyHandler handler;
    private CustomDownDialog prodialog;//自定义下载框
    private int progress;
    private boolean cancelUpdate; // 取消更新
    private boolean isError = false;// 是否出现错误


    public DownloadElement(Activity activity, String updateUrl, String apkFile, boolean isForce) {
        this.activity = activity;
        this.updateUrl = updateUrl;
        this.apkFile = apkFile;
        handler = new MyHandler(activity);
        if (isForce) {
            prodialog = new CustomDownDialog(activity);
            prodialog.setCancelable(false);
            prodialog.show();
        }
    }

    public DownloadElement(Activity activity, String urlString, boolean isForce) {
        this(activity, urlString, "app.apk", isForce);
    }

    @Override
    public void run() {
        boolean isSuccessDownLoad = false;
        File file = null;
        try {
            // 判断SD卡是否存在,并且是否具有读写权限
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                URL url = new URL(updateUrl);
                // 创建连接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                if (conn.getContentLength() > 0) {
                    // 获取文件大小
                    file = new File(StorageUtils.getStorageFile(), apkFile);
                    FileUtils.createFolder(file.getParentFile());
                    FileUtils.createFile(file);
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();
                    FileOutputStream fos = new FileOutputStream(file);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        if (numread <= 0) {
                            isSuccessDownLoad = true;
                            break;
                        } else {
                            // 计算进度条位置
                            progress = (int) ((float) count / length * 100);
                            // 更新进度
                            Message message = Message.obtain();
                            message.what = IS_DOWNLOADING;
                            message.arg1 = progress;
                            handler.sendMessage(message);
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                    if (cancelUpdate) {
                        cancelUpdate = false;
                        handler.sendEmptyMessage(DOWNLOAD_CANCEL);
                        return;
                    }
                } else {
                    conn.disconnect();
                    isError = true;
                }
            } else {

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            isError = true;
        } catch (IOException e) {
            e.printStackTrace();
            isError = true;
        }
        Log.d("isSuccessDownLoad", "isSuccessDownLoad");
        if (isSuccessDownLoad) {
            // 下载完成
            String path = MD5Util.getMD5Data(file.getName() + "_finish");
            File renameFile = new File(file.getParentFile(), path);
            file.renameTo(renameFile);
            Message message = Message.obtain();
            message.what = DOWNLOAD_FINISH;
            message.obj = renameFile;
            handler.sendMessage(message);
        } else {
            if (file != null) {
                FileUtils.deleteFile(file);
            }
            if (isError) {
                // 下载错误
                handler.sendEmptyMessage(DOWNLOAD_ERROR);
            } else if (cancelUpdate) {
                // 什么也不做
            }
        }
    }


    class MyHandler extends Handler {
        private Activity activity;
        private NotificationManager manager;
        private Notification notification;
        private Notification.Builder buidler;


        MyHandler(Activity activity) {
            super(Looper.getMainLooper());
            this.activity = activity;
            if (prodialog == null) {
                buidler = new Notification.Builder(activity);
                manager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
            }
        }

        private void showNotification(PendingIntent intent, String content, int progress) {
            // 需要注意build()是在APIlevel16及之后增加的,API11可以使用getNotificatin()来替代
            notification = buidler.setSmallIcon(R.mipmap.icon_my_app).setTicker("开始下载")
                    .setContentTitle(activity.getResources().getString(R.string.app_name))
                    .setContentIntent(intent).setContentText(content).setProgress(100, progress, false)
                    .getNotification();
            // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。
            notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
            manager.notify(0, notification);
        }

        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            if (!Thread.currentThread().isInterrupted()) {
                switch (msg.what) {
                    case IS_DOWNLOADING:
                        //更新下载进度
                        prodialog.setProgressBar(msg.arg1);
                        break;
                    case DOWNLOAD_CANCEL:
                        //取消下载
                        deleteApk();
                        break;
                    case DOWNLOAD_FINISH:
                        //下载完成
                        prodialog.dismiss();
                        File file = (File) msg.obj;
                        if (file.exists()) {
                            installApk(activity, file, true);
//                            activity.this.finish();
                        }
                        break;

                    case DOWNLOAD_ERROR:
                        //下载出错
                        if (prodialog.isShowing()) {
                            prodialog.dismiss();
                        }
                        break;
                }
            }
        }
    }

    private void deleteApk() {
        //删除下载还没完成的文件
        FileUtils.deleteFile(new File(StorageUtils.getStorageFile(), apkFile));
    }

    private void installApk(Context context, File apkfile, boolean isMust) {
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        context.startActivity(i);
        if (isMust) {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}

别忘了添加权限

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

几个File工具类:

/*
 * This class is used to manage the file and the file operations.
 */

public class FileUtils
{

   public final static int DEFAULT_FILE_OPERATE_MODE = 0;

   public final static int IGNORE_NOT_RECREATE_MODE = 1;

   public final static int IGNORE_AND_RECREATE_MODE = 2;

   public final static int NOT_IGNORE_RECREATE_MODE = 3;

   private final static boolean DEFAULT_IGNORE_STYLE = false;

   private final static boolean DEFAULT_AUTO_CREATE_DIRECTORY = true;
   
   /** 分隔符. */
   public final static String FILE_EXTENSION_SEPARATOR = ".";

   // ============== create file and dirctory==================
   /**
    * @param file
    * @throws IOException
    */
   public static void createFile(File file, int mode) throws IOException
   {

      if (file == null || TextUtils.isEmpty(file.getAbsolutePath()) || file
            .isDirectory())
      {
         return;
      }
      if (mode == IGNORE_NOT_RECREATE_MODE || mode == IGNORE_AND_RECREATE_MODE)
      {
         file = new File(StorageUtils.getStorageFile(), file.getAbsolutePath());
      }
      if (mode == IGNORE_AND_RECREATE_MODE)
      {
         deleteFile(file);
      }
      file.createNewFile();
   }

   /**
    * @param filePath
    * @param mode
    * @throws IOException
    */
   public static void createFile(String filePath, int mode) throws IOException
   {

      createFile(new File(filePath), mode);
   }

   /**
    * @param filePath
    * @throws IOException
    */
   public static void createFile(File filePath) throws IOException
   {

      createFile(filePath, DEFAULT_FILE_OPERATE_MODE);
   }

   /**
    * @param filePath
    * @throws IOException
    */
   public static void createFile(String filePath) throws IOException
   {

      createFile(new File(filePath));
   }

   /**
    * To create a folder or more.
    * 
    * @param folder
    * @param mode
    */
   public static void createFolder(File folder, int mode)
   {

      if (folder == null || TextUtils.isEmpty(folder.getAbsolutePath()))
      {
         return;
      }
      if (folder.isFile())
      {
         return;
      }
      if (mode == IGNORE_NOT_RECREATE_MODE || mode == IGNORE_AND_RECREATE_MODE)
      {
         folder = new File(StorageUtils.getStorageFile(), folder.getAbsolutePath());
      }
      if (mode == IGNORE_AND_RECREATE_MODE)
      {
         deleteFolder(folder);
      }
      folder.mkdirs();

   }

   /**
    * @param folder
    * @param mode
    */
   public static void createFolder(String folder, int mode)
   {

      createFolder(new File(folder), mode);
   }

   /**
    * @param folder
    */
   public static void createFolder(File folder)
   {

      createFolder(folder, DEFAULT_FILE_OPERATE_MODE);
   }

   /**
    * @param folder
    */
   public static void createFolder(String folder)
   {

      createFolder(new File(folder));
   }

   // ============== delete file and dirctory==================
   /**
    * delete a file.
    * 
    * @param file
    */
   public static void deleteFile(File file)
   {

      if (file == null || TextUtils.isEmpty(file.getAbsolutePath()))
      {
         return;
      }
      if (file.exists())
      {
         if (file.isFile())
         {
            file.delete();
         }
      }
   }

   /**
    * @param filePath
    */
   public static void deleteFile(String filePath)
   {

      if (!TextUtils.isEmpty(filePath))
      {
         deleteFile(new File(filePath));
      }
   }

   /**
    * delete folder.
    * 
    * @param folder
    */
   public static void deleteFolder(File folder)
   {

      if (folder == null || TextUtils.isEmpty(folder.getAbsolutePath()))
      {
         return;
      }
      if (folder.exists())
      {
         if (folder.isDirectory())
         {
            File[] files = folder.listFiles();
            if (files != null)
            {
               for (File file : files)
               {
                  deleteFolder(file);
               }
            }
            folder.delete();
         } else
         {
            deleteFile(folder);
         }
      }
   }

   /**
    * @param folderPath
    */
   public static void deleteFolder(String folderPath)
   {

      if (!TextUtils.isEmpty(folderPath))
      {
         deleteFolder(new File(folderPath));
      }
   }

   // ===========find file in order to extendsions at the end=================
   /**
    * In order to "end" At the end.
    * 
    * @return
    */
   public static List<File> getAllWithEnd(File file, boolean ignore, String... extensions)
   {

      if (TextUtils.isEmpty(file.getAbsolutePath()))
      {
         return null;
      }
      for (String extension : extensions)
      {
         if (TextUtils.isEmpty(extension))
         {
            return null;
         }
      }
      if (ignore)
      {
         file = new File(StorageUtils.getStorageFile(), file.getAbsolutePath());
      }
      if ((!file.exists()) && file.isDirectory())
      {
         return null;
      }
      List<File> files = new ArrayList<File>();
      fileFilter(file, files, extensions);
      return files;

   }

   /**
    * @param path
    * @param extensions
    * @param ignore
    * @return
    */
   public static List<File> getAllWithEnd(String path, boolean ignore, String... extensions)
   {

      return getAllWithEnd(new File(path), ignore, extensions);
   }

   /**
    * @param file
    * @param extensions
    * @return
    */
   public static List<File> getAllWithEnd(File file, String... extensions)
   {

      return getAllWithEnd(file, DEFAULT_IGNORE_STYLE, extensions);
   }

   /**
    * @param file
    * @param extensions
    * @return
    */
   public static List<File> getAllWithEnd(String file, String... extensions)
   {

      return getAllWithEnd(new File(file), DEFAULT_IGNORE_STYLE, extensions);
   }

   /**
    * filter the file.
    * 
    * @param file
    * @param extensions
    * @param files
    */
   public static void fileFilter(File file, List<File> files, String... extensions)
   {

      if (!file.isDirectory())
      {
         return;
      }
      File[] allFiles = file.listFiles();
      File[] allExtensionFiles = file.listFiles(new MyFileFilter(extensions));
      if (allExtensionFiles != null)
      {
         for (File single : allExtensionFiles)
         {
            files.add(single);
         }
      }
      if (allFiles != null)
      {
         for (File single : allFiles)
         {
            if (single.isDirectory())
            {
               fileFilter(single, files, extensions);
            }
         }
      }
   }

   // ===========copy assert to a storage=================
   /**
    * The assert directory, copy files to a storage card.
    * 
    * @param strAssetsFilePath
    * @param strDesFilePath
    * @return
    */
   public boolean assetsCopyData(String strAssetsFilePath, String strDesFilePath)
   {

      boolean bIsSuc = true;
      InputStream inputStream = null;
      OutputStream outputStream = null;

      File file = new File(strDesFilePath);
      if (!file.exists())
      {
         try
         {
            file.createNewFile();
            Runtime.getRuntime().exec("chmod 766 " + file);
         } catch (IOException e)
         {
            bIsSuc = false;
         }

      } else
      {// 存在
         return true;
      }

      try
      {
         inputStream = MyApplication.mAppContext.getAssets()
               .open(strAssetsFilePath);
         outputStream = new FileOutputStream(file);

         int nLen = 0;

         byte[] buff = new byte[1024 * 1];
         while ((nLen = inputStream.read(buff)) > 0)
         {
            outputStream.write(buff, 0, nLen);
         }

         // 完成
      } catch (IOException e)
      {
         bIsSuc = false;
      } finally
      {
         try
         {
            if (outputStream != null)
            {
               outputStream.close();
            }

            if (inputStream != null)
            {
               inputStream.close();
            }
         } catch (IOException e)
         {
            bIsSuc = false;
         }

      }

      return bIsSuc;
   }

   // ===========copy single file.=================
   /**
    * To copy single file.
    * 
    * @param src
    * @param dst
    * @return
    * @throws IOException
    */
   public static boolean copyFile(File src, File dst) throws IOException
   {

      if ((!src.exists()) || src.isDirectory() || dst.isDirectory())
      {
         return false;
      }
      if (!dst.exists())
      {
         dst.getParentFile().mkdirs();
         dst.createNewFile();
         // return false;
      }
      FileInputStream inputStream = null;
      inputStream = new FileInputStream(src);
      return copyFile(inputStream, dst);
   }

   /**
    * 从输入流复制文件
    * 
    * @param inputStream
    * @param dst
    * @return
    * @throws IOException
    */
   public static boolean copyFile(InputStream inputStream, File dst) throws IOException
   {

      FileOutputStream outputStream = null;
      outputStream = new FileOutputStream(dst);
      int readLen = 0;
      byte[] buf = new byte[1024];
      while ((readLen = inputStream.read(buf)) != -1)
      {
         outputStream.write(buf, 0, readLen);
      }
      outputStream.flush();
      inputStream.close();
      outputStream.close();
      return true;
   }

   /**
    * @param src
    * @param dst
    * @return
    * @throws IOException
    */
   public static boolean copyFile(String src, String dst) throws IOException
   {

      return copyFile(new File(src), new File(dst));
   }

   // ===========copy folder to storage=================
   /**
    * To copy the folder.
    * 
    * @param srcDir
    * @param destDir
    * @param auto
    * @return
    * @throws IOException
    */
   public static boolean copyFolder(File srcDir, File destDir, boolean auto) throws IOException
   {

      if ((!srcDir.exists()))
      {
         return false;
      }
      if (srcDir.isFile() || destDir.isFile())
         return false;// 判断是否是目录
      if (!destDir.exists())
      {
         if (auto)
         {
            destDir.mkdirs();
         } else
         {
            return false;// 判断目标目录是否存在
         }
      }
      File[] srcFiles = srcDir.listFiles();
      int len = srcFiles.length;
      for (int i = 0; i < len; i++)
      {
         if (srcFiles[i].isFile())
         {
            // 获得目标文件
            File destFile = new File(destDir.getPath() + "//" + srcFiles[i].getName());
            copyFile(srcFiles[i], destFile);
         } else if (srcFiles[i].isDirectory())
         {
            File theDestDir = new File(destDir.getPath() + "//" + srcFiles[i].getName());
            copyFolder(srcFiles[i], theDestDir, auto);
         }
      }
      return true;
   }

   /**
    * @param srcDir
    * @param desDir
    * @param auto
    * @return
    * @throws IOException
    */
   public static boolean copyFolder(String srcDir, String desDir, boolean auto) throws IOException
   {

      return copyFolder(new File(srcDir), new File(desDir), auto);
   }

   /**
    * @param srcDir
    * @param desDir
    * @return
    * @throws IOException
    */
   public static boolean copyFolder(File srcDir, File desDir) throws IOException
   {

      return copyFolder(srcDir, desDir, DEFAULT_AUTO_CREATE_DIRECTORY);
   }

   /**
    * @param srcDir
    * @param desDir
    * @return
    * @throws IOException
    */
   public static boolean copyFolder(String srcDir, String desDir) throws IOException
   {

      return copyFolder(srcDir, desDir, DEFAULT_AUTO_CREATE_DIRECTORY);
   }

   // ===========move single file to storage=================
   /**
    * To move the single file.
    * 
    * @param src
    * @param dst
    * @return
    */
   public static boolean moveFile(File src, File dst, boolean isDeleteOld)
   {

      boolean isCopy = false;
      isCopy = src.renameTo(dst);
      if (!isCopy)
      {
         return false;
      }
      if (isDeleteOld)
      {
         deleteFile(src);
      }
      return true;
   }

   /**
    * @param src
    * @param dst
    * @return
    */
   public static boolean moveFile(String src, String dst, boolean isDeleteOld)
   {

      return moveFile(new File(src), new File(dst), isDeleteOld);
   }

   // ===========move folder to storage=================
   /**
    * To move the folder.
    * 
    * @param srcDir
    * @param destDir
    * @param auto
    * @return
    */
   public static boolean moveFolder(File srcDir, File destDir, boolean auto, boolean isDeleteOld)
   {

      if (srcDir.isFile() || destDir.isFile())
      {
         return false;
      }
      if (!srcDir.exists())
      {
         return false;
      }
      if (!destDir.exists())
      {
         if (auto)
         {
            destDir.mkdirs();
         } else
         {
            return false;
         }
      }
      File[] srcDirFiles = srcDir.listFiles();
      int len = srcDirFiles.length;
      if (len <= 0)
      {
         srcDir.delete();
      }
      for (int i = 0; i < len; i++)
      {
         if (srcDirFiles[i].isFile())
         {
            File oneDestFile = new File(destDir.getPath() + "//" + srcDirFiles[i].getName());
            moveFile(srcDirFiles[i], oneDestFile, isDeleteOld);
         } else if (srcDirFiles[i].isDirectory())
         {
            File oneDestFile = new File(destDir.getPath() + "//" + srcDirFiles[i].getName());
            moveFolder(srcDirFiles[i], oneDestFile, auto, isDeleteOld);
            srcDirFiles[i].renameTo(oneDestFile);
            if (isDeleteOld)
            {
               deleteFolder(srcDirFiles[i]);
            }
         }

      }
      if (srcDir.exists())
      {
         srcDir.renameTo(destDir);
         if (isDeleteOld)
         {
            srcDir.delete();
         }
      }
      return true;
   }

   /**
    * @param src
    * @param dst
    * @param auto
    * @return
    */
   public static boolean moveFolder(String src, String dst, boolean auto, boolean isDeleteOld)
   {

      return moveFolder(new File(src), new File(dst), isDeleteOld);
   }

   /**
    * @param src
    * @param dst
    * @return
    */
   public static boolean moveFolder(File src, File dst, boolean isDeleteOld)
   {

      return moveFolder(src, dst, DEFAULT_AUTO_CREATE_DIRECTORY, isDeleteOld);
   }

   /**
    * @param src
    * @param dst
    * @return
    */
   public static boolean moveFolder(String src, String dst, boolean isDeleteOld)
   {

      return moveFolder(new File(src), new File(dst), DEFAULT_AUTO_CREATE_DIRECTORY, isDeleteOld);
   }

   // ===========get private directory=================
   /**
    * To get private directory.
    * 
    * @return
    */
   public static File getPrivateDir()
   {

      return MyApplication.mAppContext.getFilesDir();
   }


   // 格式化url
   public static String formatUrl(String url)
   {

      String[] string = url.split("\\?");
      if (string.length > 0)
      {
         return string[0];
      }
      return url;
   }

   /**
    * 获取文件大小
    * 
    * @param file
    * @return
    * @throws Exception
    */
   public static long getFileSize(File file) throws Exception
   {

      long size = 0;
      if (file.exists())
      {
         size = file.length();
      } else
      {
         file.createNewFile();
         Log.e("获取文件大小", "文件不存在!");
      }
      return size;
   }

   /**
    * 获取文件夹大小
    * 
    * @param f
    * @return
    * @throws Exception
    */
   public static long getFileSizes(File f) throws Exception
   {

      long size = 0;
      File flist[] = f.listFiles();
      if (flist == null)
      {
         return 0;
      }
      for (int i = 0; i < flist.length; i++)
      {
         if (flist[i].isDirectory())
         {
            size = size + getFileSizes(flist[i]);
         } else
         {
            size = size + getFileSize(flist[i]);
         }
      }
      return size;
   }
   
   /**
    * 检测是否有SD卡权限
    * @return 是否有SD卡权限
    */
   public static boolean hasSdcard()
   {
      if (android.os.Environment.getExternalStorageState()
            .equals(android.os.Environment.MEDIA_MOUNTED))
      {
         return true;
      }
      return false;
   }
   
   /**
    * 删除指定目录中特定的文件
    * @param dir
    * @param filter
    */
   public static void delete(String dir, FilenameFilter filter) {
      if (TextUtils.isEmpty(dir))
         return;
      File file = new File(dir);
      if (!file.exists())
         return;
      if (file.isFile())
         file.delete();
      if (!file.isDirectory())
         return;

      File[] lists = null;
      if (filter != null)
         lists = file.listFiles(filter);
      else
         lists = file.listFiles();

      if (lists == null)
         return;
      for (File f : lists) {
         if (f.isFile()) {
            f.delete();
         }
      }
   }
   
   /**
    * 获得不带扩展名的文件名称
    * @param filePath 文件路径
    * @return
    */
   public static String getFileNameWithoutExtension(String filePath) {
      if (TextUtils.isEmpty(filePath)) {
         return filePath;
      }
      int extenPosi = filePath.lastIndexOf(FILE_EXTENSION_SEPARATOR);
      int filePosi = filePath.lastIndexOf(File.separator);
      if (filePosi == -1) {
         return (extenPosi == -1 ? filePath : filePath.substring(0,
               extenPosi));
      }
      if (extenPosi == -1) {
         return filePath.substring(filePosi + 1);
      }
      return (filePosi < extenPosi ? filePath.substring(filePosi + 1,
            extenPosi) : filePath.substring(filePosi + 1));
   }
   
}


import com.chw.app.MyApplication;

import java.io.File;

/*
 * This class is used to manager storage.
 */

public class StorageUtils {

	private final static int DEFAULT_DISPLAY_FORMAT = 0;  //byte

	public final static int DISPLAY_BYTE_FORMAT = 0; // byte

	public final static int DISPLAY_KB_FORMAT = 1; // KB

	public final static int DISPLAY_MB_FORMAT = 2; // MB

	public final static int DISPLAY_GB_FORMAT = 3; // GB

	public final static int DISPLAY_TB_FORMAT = 4; // TB

	private final static float DEFAULT_MULTIPLE = 1024.0f; // 1024 unit

	private final static float MULTIPLE_1000 = 1000.0f;   // 1000 unit

	private final static int DEFAULT_DISPLAY_MULTIPLE = 0; // defualt 1024 unit

	public final static int DISPLAY_1000_MULTIPLE = 1; // 1000 unit

	public final static int DISPLAY_1024_MULTIPLE = 0; // 1024 unit
	
	private final static int KEEP_DECIMAL_POINT_MULTIPLE = 100;

	/**
	 * To judge the storage is mounted.
	 * 
	 * @return
	 */
	public static boolean isMount()
	{

		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	/**
	 * To get the storage directory. This is return String.
	 * 
	 * @return
	 */
	public static String getStorageDirectory()
	{

		File file = getStorageFile();
		if (file == null) {
			return null;
		}
		return file.getAbsolutePath();
	}

	/**
	 * To get the storage directory This is return File.
	 * 
	 * @return
	 */
	public static File getStorageFile()
	{

		if (!isMount()) {
			return null;
		}
		return Environment.getExternalStorageDirectory();
	}

	/**
	 * To get the storage total volume.
	 * 
	 * @param format
	 * @param multiple 
	 * @return
	 */
	public static float getStorageVolume(int format, int multiple)
	{

		float unit = DEFAULT_MULTIPLE;
		double total_volume = 0;
		File file = getStorageFile();
		StatFs sFs = new StatFs(file.getPath());
		long blockSize = sFs.getBlockSize();
		int total = sFs.getBlockCount();
		long size = total * blockSize;
		if (multiple == DISPLAY_1024_MULTIPLE) {
			unit = DEFAULT_MULTIPLE;
		}
		else if (multiple == DISPLAY_1000_MULTIPLE) {
			unit = MULTIPLE_1000;
		}
		switch (format)
		{
			case DISPLAY_BYTE_FORMAT:
				total_volume = size;
				break;

			case DISPLAY_KB_FORMAT:
				total_volume = size / unit;
				break;

			case DISPLAY_MB_FORMAT:
				total_volume = size / unit / unit;
				break;

			case DISPLAY_GB_FORMAT:
				total_volume = size / unit / unit / unit;
				break;

			case DISPLAY_TB_FORMAT:
				total_volume = size / unit / unit / unit / unit;
				break;
		}
		return (float) Math.round(total_volume*KEEP_DECIMAL_POINT_MULTIPLE)/KEEP_DECIMAL_POINT_MULTIPLE;
	}

	/**
	 * @return
	 */
	public static float getStorageVolume()
	{

		return getStorageVolume(DEFAULT_DISPLAY_FORMAT,
				DEFAULT_DISPLAY_MULTIPLE);
	}

	/**
	 * To get the storage avialable volume.
	 * 
	 * @param format
	 * @param multiple
	 * @return
	 */
	public static float getUsableVolumn(int format, int multiple)
	{

		float unit = DEFAULT_MULTIPLE;
		double avialable_volume = 0;
		File file = getStorageFile();
		StatFs sFs = new StatFs(file.getPath());
		long blockSize = sFs.getBlockSize();
		int avialable_blocks = sFs.getAvailableBlocks();
		long avialable = avialable_blocks * blockSize;
		if (multiple == DISPLAY_1024_MULTIPLE) {
			unit = DEFAULT_MULTIPLE;
		}
		else if (multiple == DISPLAY_1000_MULTIPLE) {
			unit = MULTIPLE_1000;
		}
		switch (format)
		{
			case DISPLAY_BYTE_FORMAT:
				avialable_volume = avialable;
				break;

			case DISPLAY_KB_FORMAT:
				avialable_volume = avialable / unit;
				break;

			case DISPLAY_MB_FORMAT:
				avialable_volume = avialable / unit / unit;
				break;

			case DISPLAY_GB_FORMAT:
				avialable_volume = avialable / unit / unit / unit;
				break;

			case DISPLAY_TB_FORMAT:
				avialable_volume = avialable / unit / unit / unit / unit;
				break;
		}
		return (float) Math.round(avialable_volume*KEEP_DECIMAL_POINT_MULTIPLE)/KEEP_DECIMAL_POINT_MULTIPLE;
	}

	/**
	 * @return
	 */
	public static float getUsableVolumn()
	{

		return getUsableVolumn(DEFAULT_DISPLAY_FORMAT, DEFAULT_DISPLAY_MULTIPLE);
	}

    private long getAvailMemory() {// 获取当前android可用内存大小

        ActivityManager am = (ActivityManager) MyApplication.mAppContext.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        // mi.availMem; 当前系统的可用内�?
        Log.d("MyApplication", "当前系统可用内存--->" + mi.availMem);
        return mi.availMem;
    }
}
public class MyFileFilter implements FilenameFilter {

	private List<String> extensions = new ArrayList<String>();

	public MyFileFilter(String... extensions)
	{

		for(String extension:extensions)
		{
			this.extensions.add(extension);
		}
	}

	@Override
	public boolean accept(File dir, String filename)
	{

		// TODO Auto-generated method stub
		boolean flag = false;
		for(String extension:extensions)
		{
			if(filename.endsWith(extension))
			{
				flag = true;
				break;
			}
		}
		return flag;
	}
}
/**
 * MD5字符串加密工具类
 */
public class MD5Util {

	/**
	 * MD5 加密
	 * 
	 * @param data
	 * @return 加密字符串
	 */
	public static String getMD5Data(String data) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(data.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	/**
	 * MD5循环加密3次
	 * 
	 * @param data
	 * @return
	 */
	public static String getMD5ThreeData(String data) {

		return getMD5Data(getMD5Data(getMD5Data(data)));
	}
}

下载框

public class CustomDownDialog extends Dialog {
    private LinearLayout ll_down_load_top;
    private ProgressBar progressBar;
    private TextView tv_current;
    private TextView tv_cancel;

    public CustomDownDialog(Context context) {
        super(context, R.style.loadindDialog);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_download_dilog);
        initView();
    }

    private void initView() {
        //模式对话框
        setCancelable(false);

        //更新进度时使用
        ll_down_load_top = (LinearLayout) findViewById(R.id.ll_down_load_top);
        progressBar = (ProgressBar) findViewById(R.id.update_progress);
        tv_current = (TextView) findViewById(R.id.tv_current);
        tv_cancel = (TextView) findViewById(R.id.tv_cancel);

    }

    /**
     * 更新进度条
     *
     * @param current
     */
    public void setProgressBar(int current) {
        progressBar.setProgress(current);
        //计算
        tv_current.setText("已更新"+current+"%");
    }

    /**
     * 注册点击事件 取消更新
     * @param click
     */
    public CustomDownDialog setClick(View.OnClickListener click){
        this.tv_cancel.setOnClickListener(click);
        return this;
    }
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp">

    <!--软件更新-->
    <LinearLayout
        android:id="@+id/ll_down_load_top"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/soft_down_bg"
        android:orientation="vertical"
        android:visibility="visible">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:text="软件更新"
            android:textColor="@color/black"
            android:textSize="20sp"
            android:textStyle="bold"/>

        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:background="#7C7C7C"/>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingLeft="10dp"
            android:paddingRight="10dp">

            <ProgressBar
                android:id="@+id/update_progress"
                style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:layout_marginTop="20dp"/>

            <TextView
                android:id="@+id/tv_current"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@id/update_progress"
                android:layout_marginBottom="15dp"
                android:paddingRight="10dp"
                android:text="已更新0%"
                android:textColor="#7C7C7C"
                android:textSize="14sp"/>


        </RelativeLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:background="#7C7C7C"/>

        <TextView
            android:id="@+id/tv_cancel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:layout_marginTop="15dp"
            android:gravity="center"
            android:text="取消更新"
            android:textColor="#1096bb"
            android:textSize="18sp"
            android:visibility="gone"/>
    </LinearLayout>

</RelativeLayout>

soft_down_bg:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#FCFCFC"/>
    <corners android:radius="8dp"/>
</shape>

loadindDialog:

 <style name="loadindDialog" parent="android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@color/transparent</item>
        <item name="android:backgroundDimEnabled">true</item>
    </style>

最后:

是否更新的提示框:

public void updateAPKDialog(String updateContentString, final String url,
                                final Activity activty, final boolean isForceUpdate) {
        Dialog dialog;
        DzDialog.Builder customBuilder = new DzDialog.Builder(activty);
        customBuilder.setTitle(isForceUpdate ? "版本已过期,请尽快升级" : "有新的版本");
        customBuilder.setMessage(updateContentString);
        customBuilder.setNegativeButton(isForceUpdate ? "退出" : "暂不升级",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (isForceUpdate) {
                            activty.finish();
                        }
                    }
                }).setPositiveButton("升级",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // 更新
                        dialog.dismiss();
                        new DownloadFileThread(activty, url, isForceUpdate).start();
                    }
                });
        dialog = customBuilder.create(R.layout.dialog);
        if (isForceUpdate) {
            dialog.setCancelable(false);
        }
        dialog.show();
    }

放到通用工具类:

CommonUtil.getInstance().updateAPKDialog("更新内容",url,MainActivity.this,true);







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值