通常在使用service更新應用時最常出現的問題就是Notification進度的更新問題、service在什么時間關閉以及需要我們自己在Service中創建新的線程處理耗時操作,當然這種也是可以實現的但是會顯得略微繁瑣
經過對比發現可以使用IntentService已經實現了對耗時操作的包裝出來,我們只需要實現IntentService中的onHandleIntent方法就可以在其中進行耗時操作的處理,在處理下載問題時發現在使用intentservice時暫時沒有發現可以優雅的進行進度回調的實現方法,所以我這邊使用了本地廣播的形式來進行進度刷新。
添加了當前狀態判斷,當應用處于前臺狀態時直接進行安裝,當應用處于后臺時彈出notification彈窗點擊后安裝,示例如下圖:

先創建廣播
public static class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case ACTION_TYPE_PREPARE: if (downloadCallback != null) { downloadCallback.onPrepare(); } break; case ACTION_TYPE_PROGRESS: int progress = intent.getIntExtra("progress", 0);// Log.d("progress", "|- " + progress + " -|"); if (downloadCallback != null) { downloadCallback.onProgress(progress); } break; case ACTION_TYPE_COMPLETE: String file_path = intent.getStringExtra("file_path"); if (!TextUtils.isEmpty(file_path)) { File file = new File(file_path); if (file.exists()) { if (downloadCallback != null) { downloadCallback.onComplete(file); } } } break; case ACTION_TYPE_FAIL: String error = intent.getStringExtra("error"); if (downloadCallback != null) { downloadCallback.onFail(error + ""); } break; } }然后在IntentService中初始化本地廣播并發送信息
@Override public void onCreate() { super.onCreate(); mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); } // 在下載進度刷新的地方進行回調 private void progress(int progress) { Intent intent = new Intent(FileDownloaderManager.ACTION_TYPE_PROGRESS); intent.putExtra("progress", progress); mLocalBroadcastManager.sendBroadcast(intent); } private void downApk(String url) { ..... ..... progress(progress); ..... ..... }在activity中使用
mLocalBroadcastManager = LocalBroadcastManager.getInstance(mContext);mBroadcastReceiver = new MyBroadcastReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction(ACTION_TYPE_PREPARE);intentFilter.addAction(ACTION_TYPE_PROGRESS);intentFilter.addAction(ACTION_TYPE_COMPLETE);intentFilter.addAction(ACTION_TYPE_FAIL);mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, intentFilter);// ondestory時調用mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
以上源碼已進行封裝,方便使用具體操作步驟如下:
|- 初始化及注冊回調
//初始化文件下載管理類FileDownloaderManager.init(context)// 注冊下載進度監聽,并開啟廣播接收FileDownloaderManager.registerDownload(object : FileDownloaderManager.DownloadCallback { override fun onComplete(file: File) = mainView.downloadSucc(file) override fun onFail(msg: String?) = Unit override fun onProgress(progress: Int) = mainView.onProgress(progress) override fun onPrepare() = Unit })//開始下載FileDownloaderManager.download(url)|- 在下載完成后進行資源重置
FileDownloaderManager.unbinder()
源碼地址:源碼地址
文檔地址:文檔地址
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答