您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
怎么在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。