kad*_*dir 6 android design-patterns
什么设计模式将是智能的,其中存在以下组件(简化):
3组件
- GUI
- 数据获取器
- 数据库
我无法访问Internet中的服务器,它只是一个数据源.放在Internet中的数据总是较新的,本地数据库只是Internet中的数据的副本(缓存).GUI可以请求和更新本地缓存,类似服务的组件然后异步提取最新数据,这可能需要一段时间.GUI仅显示本地数据库中的数据,可以同步获取.
所以我的问题是,您可以使用哪些类来进行长期运行Service with Progressbar功能?这种"问题"有更好的设计吗?有更好的做法吗?
在类似服务的组件上:
jobId
来指示正在后台处理的作业jobId
. 该服务的实现可以返回状态、完成百分比或任何其他相关信息,告诉调用者更新过程的当前状态。该方法的实现需要能够报告增量进度(例如报告本地存储中的增量存储),以便做出准确的进度条,否则UI最多只能显示旋转的进度条。
AsyncTask
用法,即在后台执行更新并在完成时向用户报告。如果此操作可能需要一段时间,您可以通过Android通知栏或推送通知来实现更新完成。假设您有获取更新进度的接口,您可以利用AsyncTask onProgressUpdate来报告更新进度。该方法是专门为此设计的。
您的步骤大致如下:
onProgressUpdate
。AsyncTask 大致看起来像
public class GetUpdateStatusAsyncTask extends AsyncTask {
protected Integer doInBackground(Integer... param) {
// this is the jobId that you get from the previous AsyncTask that you use to kick off the
// the update process
int jobId = param[0];
double percentCompleted = fetchStatus(jobId);
while(percentCompleted != 100.00) {
publishProgress(percentCompleted);
}
// return status code
return 1;
}
protected void onProgressUpdate(Double... progress) {
// set the progressBar here
}
protected void onPostExecute(Long result) {
// done, handle status code
}
private double fetchStatus(int jobId) {
double percentCompleted = 0.0;
// call interface to get the update based on the jobId
// return percentCompleted status or make a more complex object if you need
// more detail info
return percentCompleted;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1547 次 |
最近记录: |