怎么在Android中利用IntentService對apk進(jìn)行更新?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
創(chuàng)新互聯(lián)的客戶來自各行各業(yè),為了共同目標(biāo),我們在工作上密切配合,從創(chuàng)業(yè)型小企業(yè)到企事業(yè)單位,感謝他們對我們的要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來驚喜。專業(yè)領(lǐng)域包括成都做網(wǎng)站、成都網(wǎng)站建設(shè)、電商網(wǎng)站開發(fā)、微信營銷、系統(tǒng)平臺(tái)開發(fā)。創(chuàng)建廣播
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中初始化本地廣播并發(fā)送信息
@Override public void onCreate() { super.onCreate(); mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); } // 在下載進(jìn)度刷新的地方進(jìn)行回調(diào) 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時(shí)調(diào)用 mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
以上源碼已進(jìn)行封裝,方便使用具體操作步驟如下:
|- 初始化及注冊回調(diào)
//初始化文件下載管理類 FileDownloaderManager.init(context) // 注冊下載進(jìn)度監(jiān)聽,并開啟廣播接收 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)
|- 在下載完成后進(jìn)行資源重置
FileDownloaderManager.unbinder()
看完上述內(nèi)容,你們掌握怎么在Android中利用IntentService對apk進(jìn)行更新的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!