您好,登錄后才能下訂單哦!
怎么在Android中利用IntentService對apk進行更新?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
創建廣播
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()
看完上述內容,你們掌握怎么在Android中利用IntentService對apk進行更新的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。