Android APP更新——service後臺下載、進度提示、自動安裝

檢測應用的當前版本號。與服務端最新版本號進行比較。

    /**
     * 獲取版本號    需要在Activity 中使用
     * @return 當前應用的版本號
     */
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "獲取失敗";
        }
    }

檢測本地版本號低於最新版本時。需要更新。  如下啓動service

Intent intent = new Intent(SetActivity.this, DownAPKService.class);
apkDownloadPath=new String();
 intent.putExtra("apk_url",apkDownloadPath);
 startService(intent);
DownAPKService

package com.xx.xx;


import java.io.File;
import java.text.DecimalFormat;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * @Title:DownAPKService.java
 * @Description:專用下載APK文件Service工具類,通知欄顯示進度,下載完成震動提示,並自動打開安裝界面(配合xUtils快速開發框架)
 * 
 * 需要添加權限:
 * <uses-permission android:name="android.permission.INTERNET" />
 * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 * <uses-permission android:name="android.permission.VIBRATE" />
 * 
 * 需要在<application></application>標籤下注冊服務
 * 
 * 可以在142行代碼:builder.setSmallIcon(R.drawable.ic_launcher);中修改自己應用的圖標

 * @author LEI-LEI  
 * @version   1.0 
 * 2016-7-6 下午4:54:16   
 */

public class DownAPKService extends Service {

        private final int NotificationID = 0x10000;
        private NotificationManager mNotificationManager = null;
        private NotificationCompat.Builder builder;

        private HttpHandler<File> mDownLoadHelper;

        // 文件下載路徑
        private String APK_url = "";
        // 文件保存路徑(如果有SD卡就保存SD卡,如果沒有SD卡就保存到手機包名下的路徑)
        private String APK_dir = "";

        @Override
        public IBinder onBind(Intent intent) {
                return null;
        }

 
        @Override
        public void onCreate() {
                super.onCreate();
                initAPKDir();// 創建保存路徑
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
                System.out.println("onStartCommand");
                // 接收Intent傳來的參數:
//                APK_url = intent.getStringExtra("apk_url");

                DownFile(<span style="font-family: Arial, Helvetica, sans-serif;">APK_url </span>, APK_dir + "Club.apk");

                return super.onStartCommand(intent, flags, startId);
        }

        private void initAPKDir() {
                /**
                 * 創建路徑的時候一定要用[/],不能使用[\],但是創建文件夾加文件的時候可以使用[\].
                 * [/]符號是Linux系統路徑分隔符,而[\]是windows系統路徑分隔符 Android內核是Linux.
                 */
                if (isHasSdcard())// 判斷是否插入SD卡
                	{
                	APK_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Club/download/";// 保存到SD卡路徑下
                	}
                else{
                	APK_dir = getApplicationContext().getFilesDir().getAbsolutePath() + "/Club/download/";// 保存到app的包名路徑下
                }
                File destDir = new File(APK_dir);
                if (!destDir.exists()) {// 判斷文件夾是否存在
                        destDir.mkdirs();
                }
        }

        /**
         * 
         * @Description:判斷是否插入SD卡
         */
        private boolean isHasSdcard() {
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                        return true;
                } else {
                        return false;
                }
        }

        private void DownFile(String file_url, String target_name) {
                mDownLoadHelper = new HttpUtils().download(file_url, target_name, true, true, new RequestCallBack<File>() {

                        @Override
                        public void onStart() {
                                super.onStart();
                                System.out.println("開始下載文件");
                                mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                                builder = new NotificationCompat.Builder(getApplicationContext());
                                builder.setSmallIcon(R.drawable.ic_launcher);
                                builder.setTicker("正在下載新版本");
                                builder.setContentTitle(getApplicationName());
                                builder.setContentText("正在下載,請稍後...");
                                builder.setNumber(0);
                                builder.setAutoCancel(true);
                                mNotificationManager.notify(NotificationID, builder.build());

                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {
                                super.onLoading(total, current, isUploading);
                                System.out.println("文件下載中");
                                int x = Long.valueOf(current).intValue();
                                int totalS = Long.valueOf(total).intValue();
                                builder.setProgress(totalS, x, false);
                                builder.setContentInfo(getPercent(x, totalS));
                                mNotificationManager.notify(NotificationID, builder.build());
                        }

                        @Override
                        public void onSuccess(ResponseInfo<File> responseInfo) {
                                System.out.println("文件下載完成");
                                Intent installIntent = new Intent(Intent.ACTION_VIEW);
                                System.out.println(responseInfo.result.getPath());
                                Uri uri = Uri.fromFile(new File(responseInfo.result.getPath()));
                                installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
                                installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                PendingIntent mPendingIntent = PendingIntent.getActivity(DownAPKService.this, 0, installIntent, 0);
                                builder.setContentText("下載完成,請點擊安裝");
                                builder.setContentIntent(mPendingIntent);
                                mNotificationManager.notify(NotificationID, builder.build());
                                // 震動提示
                                Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                                vibrator.vibrate(1000L);// 參數是震動時間(long類型)
                                stopSelf();
                                startActivity(installIntent);// 下載完成之後自動彈出安裝界面
                                mNotificationManager.cancel(NotificationID);
                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                                System.out.println("文件下載失敗");
                                mNotificationManager.cancel(NotificationID);
                                Toast.makeText(getApplicationContext(), "下載失敗,請檢查網絡!", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancelled() {
                                super.onCancelled();
                                System.out.println("文件下載結束,停止下載器");
                                mDownLoadHelper.cancel();
                        }

                });
        }

        /**
         * 
         * @param x
         *            當前值
         * @param total
         *            總值
         * [url=home.php?mod=space&uid=7300]@return[/url] 當前百分比
         * @Description:返回百分之值
         */
        private String getPercent(int x, int total) {
                String result = "";// 接受百分比的值
                double x_double = x * 1.0;
                double tempresult = x_double / total;
                // 百分比格式,後面不足2位的用0補齊 ##.00%
                DecimalFormat df1 = new DecimalFormat("0.00%");
                result = df1.format(tempresult);
                return result;
        }

        /**
         * @return
         * @Description:獲取當前應用的名稱
         */
        private String getApplicationName() {
                PackageManager packageManager = null;
                ApplicationInfo applicationInfo = null;
                try {
                        packageManager = getApplicationContext().getPackageManager();
                        applicationInfo = packageManager.getApplicationInfo(getPackageName(), 0);
                } catch (PackageManager.NameNotFoundException e) {
                        applicationInfo = null;
                }
                String applicationName = (String) packageManager.getApplicationLabel(applicationInfo);
                return applicationName;
        }

        
        @Override
        public void onDestroy() {
                super.onDestroy();
                stopSelf();
        }

}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章