怎么在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进行更新的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!