怎么在Android中利用IntentService对apk进行更新-创新互联
怎么在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进行更新的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
分享名称:怎么在Android中利用IntentService对apk进行更新-创新互联
网站网址:http://myzitong.com/article/dpohsh.html