Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 下載進度監聽與通知欄更新:封裝可複用的下載框架

編輯:關於 Android 程式設計

下載並展示進度、完成後彈通知引導安裝,是 App 升級場景裡的固定套路。本文把這套邏輯拆成三層:回調接口、線程池管理、下載管理器,最後封裝成一個帶通知欄的更新服務。

一、下載回調接口

以 apk 下載為例,只需要關心三件事:下載中、下載成功、下載失敗。對應的接口就非常清晰:

public interface DownloadCallback {
    /** 下載成功 @param file 目標文件 */
    void onComplete(File file);

    /** 下載失敗 @param e 異常信息 */
    void onError(Exception e);

    /** 下載中 @param count 總大小 @param current 當前進度 */
    void onLoading(long count, long current);
}

二、線程池管理

也可以直接用 Executors 的靜態工廠方法,這裡選擇手動構建以便控制參數:

public class ThreadManager {
    private static ThreadPool mThreadPool;

    public static ThreadPool getThreadPool() {
        if (null == mThreadPool) {
            synchronized (ThreadManager.class) {
                if (null == mThreadPool) {
                    int cpuNum = Runtime.getRuntime().availableProcessors();
                    int count = cpuNum * 2 + 1;         // 線程數與 CPU 掛鉤
                    mThreadPool = new ThreadPool(count, count, 0);
                }
            }
        }
        return mThreadPool;
    }

    public static class ThreadPool {
        int corePoolSize;        // 核心線程數
        int maximumPoolSize;     // 最大線程數
        long keepAliveTime;      // 空閒存活時間
        private ThreadPoolExecutor executor;

        private ThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }

        private static final ThreadFactory sThreadFactory = new ThreadFactory() {
            private final AtomicInteger mCount = new AtomicInteger(1);
            public Thread newThread(Runnable r) {
                return new Thread(r, "ThreadManager #" + mCount.getAndIncrement());
            }
        };

        public void execute(Runnable r) {
            if (null == executor) {
                executor = new ThreadPoolExecutor(
                        corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
                        new LinkedBlockingQueue<Runnable>(), sThreadFactory,
                        new ThreadPoolExecutor.AbortPolicy());
            }
            executor.execute(r);
        }

        /** 從隊列中移除任務;若任務已在執行則不在隊列中,移除失敗 */
        public void cancle(Runnable r) {
            if (null != executor && null != r) {
                executor.getQueue().remove(r);
            }
        }

        public boolean isShutdown() { return executor.isShutdown(); }

        public void shutdown() { executor.shutdown(); }
    }
}

三、下載管理器

public class DownloadManager {
    private DownloadCallback callback;
    private Context context;
    private String url;
    private String fileName;

    public DownloadManager(Context context, String url, String fileName, DownloadCallback callback) {
        this.context = context;
        this.url = url;
        this.fileName = fileName;
        this.callback = callback;
    }

    public void startDownload() {
        if (null == callback) return;
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                try {
                    conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(10000);

                    long total = conn.getContentLength();
                    long curr = 0;

                    File file = new File(PathUtils.getDirectory(context, "apk"), fileName);
                    if (!file.exists()) {
                        file.createNewFile();
                    } else {
                        file.delete();               // 重新下載前先清理
                    }
                    FileOutputStream fos = new FileOutputStream(file);

                    if (200 == conn.getResponseCode()) {
                        InputStream in = conn.getInputStream();
                        byte[] buff = new byte[1024];
                        int len;
                        while ((len = in.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                            curr += len;
                            callback.onLoading(total, curr);     // 回報進度
                        }
                        in.close();
                        fos.close();
                        if (curr == total) {
                            callback.onComplete(file);
                        } else {
                            throw new Exception("curr != total");
                        }
                    } else {
                        throw new Exception("" + conn.getResponseCode());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    callback.onError(e);
                } finally {
                    if (null != conn) conn.disconnect();
                }
            }
        });
    }
}

四、兩個工具類

PathUtils 負責挑選合適的存儲目錄,並保證目錄可讀可寫:

public class PathUtils {
    public static File getDirectory(Context context, String rootDir) {
        String cachePath = context.getApplicationContext().getCacheDir().getAbsolutePath();
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            if (Build.VERSION.SDK_INT <= 8) {
                cachePath = Environment.getExternalStorageDirectory().getAbsolutePath();
            } else if (context.getApplicationContext().getExternalCacheDir() != null) {
                cachePath = context.getApplicationContext().getExternalCacheDir().getAbsolutePath();
            }
        }
        File rootF = new File(cachePath + File.separator + rootDir);
        if (!rootF.exists()) {
            rootF.mkdirs();
        }
        CmdUtils.execCmd("chmod 777 -R " + rootF.getPath());   // 放權限
        return rootF;
    }
}

public class CmdUtils {
    public static void execCmd(String cmd) {
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

五、封裝成帶通知的更新服務

這一部分用到 Notification + Service。這裡選 IntentService,好處是任務跑完會自動停止服務;同時通過發送廣播,讓 App 內其他頁面也能訂閱下載進度。

public class UpdateService extends IntentService {
    private File apkFile;
    private String url;
    private String fileName;
    private NotificationCompat.Builder builderNotification;
    private NotificationManager updateNotificationManager;
    private int appNameID;
    private int iconID;
    private PendingIntent updatePendingIntent;
    private boolean isUpdating;

    public static final String ACTION_UPDATE_PROGRESS =
            "blog.csdn.net.mchenys.mobilesafe.ACTION_UPDATE_PROGRESS";

    private Handler updateHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0: UpdateService.this.onFailNotification(); break;
                case 1: UpdateService.this.downComplete();        break;
            }
            super.handleMessage(msg);
        }
    };

    public UpdateService() { super("UpdateService"); }

    /** 對外入口 */
    public static void startUpdate(Context context, String url, String fileName) {
        Intent intent = new Intent(context, UpdateService.class);
        intent.putExtra("url", url);
        intent.putExtra("fileName", fileName);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (!this.isUpdating && intent != null) {
            initData(intent);
            initNotification();
            downloadFile(true);
        }
    }

    private void initData(Intent intent) {
        this.isUpdating = true;
        this.url = intent.getStringExtra("url");
        this.fileName = intent.getStringExtra("fileName");
        this.apkFile = new File(PathUtils.getDirectory(getApplicationContext(), "mobilesafe"), fileName);
        if (!this.apkFile.exists()) {
            try {
                this.apkFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            this.apkFile.delete();
        }
        this.appNameID = R.string.app_name;
        this.iconID = R.mipmap.ic_logo;
    }

    /** 通知欄先擺一個 0% 的樣子 */
    private void initNotification() {
        Intent updateCompletingIntent = new Intent();
        updateCompletingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        updateCompletingIntent.setClass(getApplicationContext(), UpdateService.class);
        this.updatePendingIntent = PendingIntent.getActivity(this, this.appNameID,
                updateCompletingIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        this.updateNotificationManager = (NotificationManager)
                getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        this.builderNotification = new NotificationCompat.Builder(this.getApplicationContext());
        this.builderNotification
                .setSmallIcon(this.iconID)
                .setContentTitle(getResources().getString(this.appNameID))
                .setContentIntent(updatePendingIntent)
                .setAutoCancel(true)
                .setTicker("開始更新")
                .setDefaults(1)
                .setProgress(100, 0, false)
                .setContentText("下載進度")
                .build();
        this.updateNotificationManager.notify(this.iconID, this.builderNotification.build());
    }

    /** 核心下載邏輯,append 控制是否斷點續傳 */
    private void downloadFile(final boolean append) {
        final Message message = updateHandler.obtainMessage();
        int currentSize = 0;      // 上次已下載的大小
        long readSize = 0L;       // 本次已下載
        long contentLength = 0;   // 服務器返回的總長度

        if (append) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(UpdateService.this.apkFile);
                currentSize = fis.available();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fis != null) {
                    try { fis.close(); } catch (IOException e) { e.printStackTrace(); }
                }
            }
        }

        HttpURLConnection conn = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            conn = (HttpURLConnection) new URL(UpdateService.this.url).openConnection();
            conn.setRequestProperty("User-Agent", "Android");
            if (currentSize > 0) {
                // 斷點續傳關鍵:告訴服務器從哪裡接着傳
                conn.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
            }
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(20000);
            contentLength = conn.getContentLength();

            if (conn.getResponseCode() == 404) {
                throw new Exception("Cannot find remote file:" + UpdateService.this.url);
            }

            is = conn.getInputStream();
            fos = new FileOutputStream(UpdateService.this.apkFile, append);

            byte[] buffer = new byte[8 * 1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                readSize += len;
                int progress = (int) (readSize * 100 / contentLength);
                if (progress % 8 == 0) {          // 節流,避免過於頻繁刷新通知
                    UpdateService.this.builderNotification.setProgress(100, progress, false);
                    UpdateService.this.updateNotificationManager.notify(
                            iconID, UpdateService.this.builderNotification.build());
                    sendUpdateProgress(progress);  // 廣播給其他組件
                }
            }

            if (readSize == 0L) {
                message.what = 0;
            } else if (readSize == contentLength) {
                message.what = 1;
                sendUpdateProgress(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
            message.what = 0;
        } finally {
            if (conn != null) conn.disconnect();
            IOUtils.close(is);
            IOUtils.close(fos);
            updateHandler.sendMessage(message);
        }
    }

    private void sendUpdateProgress(int progress) {
        Intent intent = new Intent(ACTION_UPDATE_PROGRESS);
        intent.putExtra("progress", progress);
        sendBroadcast(intent);
    }

    private void onFailNotification() {
        this.builderNotification
                .setSmallIcon(iconID)
                .setContentTitle("更新失敗,請重新下載")
                .setContentIntent(updatePendingIntent)
                .setAutoCancel(true)
                .setTicker("更新失敗")
                .setDefaults(1)
                .setProgress(100, 0, false)
                .setContentText("下載進度")
                .build();
        this.updateNotificationManager.notify(iconID, this.builderNotification.build());
    }

    /** 下載完成,引導用戶點擊安裝 */
    private void downComplete() {
        UpdateService.this.isUpdating = false;
        CmdUtils.execCmd("chmod 777 " + this.apkFile.getPath());

        Uri uri = Uri.fromFile(this.apkFile);
        Intent updateCompleteIntent = new Intent(Intent.ACTION_VIEW);
        updateCompleteIntent.addCategory(Intent.CATEGORY_DEFAULT);
        updateCompleteIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        this.updatePendingIntent = PendingIntent.getActivity(this, this.appNameID,
                updateCompleteIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        this.builderNotification
                .setSmallIcon(this.iconID)
                .setContentTitle(getResources().getString(this.appNameID))
                .setContentIntent(this.updatePendingIntent)
                .setAutoCancel(true)
                .setTicker("更新完成")
                .setDefaults(1)
                .setProgress(0, 0, false)
                .setContentText("更新完成,點擊安裝")
                .build();
        this.updateNotificationManager.notify(this.iconID, this.builderNotification.build());
    }
}

六、實踐中的幾點補充

1. 通知渠道:Android 8.0 起必須先創建 NotificationChannel,否則通知不會顯示;
2. FileProvider:Android 7.0 起 Uri.fromFile 傳遞文件會拋 FileUriExposedException,需要改用 FileProvider 並授予讀權限;
3. 下載權限:寫外部存儲需要 READ/WRITE_EXTERNAL_STORAGE,且在新版本上要動態申請;
4. 進度節流:示例中用「百分比能被 8 整除」來降低通知刷新頻率,實戰中更推薦按時間間隔節流,效果更穩定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved