像架构这样的服务的设计模式

kad*_*dir 6 android design-patterns

什么设计模式将是智能的,其中存在以下组件(简化):

3组件
- GUI
- 数据获取器
- 数据库

设计

我无法访问Internet中的服务器,它只是一个数据源.放在Internet中的数据总是较新的,本地数据库只是Internet中的数据的副本(缓存).GUI可以请求和更新本地缓存,类似服务的组件然后异步提取最新数据,这可能需要一段时间.GUI仅显示本地数据库中的数据,可以同步获取.

所以我的问题是,您可以使用哪些类来进行长期运行Service with Progressbar功能?这种"问题"有更好的设计吗?有更好的做法吗?

mom*_*omo 1

在类似服务的组件上:

  • 用于启动更新过程的接口(方法)。通常,此服务会返回 ajobId来指示正在后台处理的作业
  • 另一个接口(方法)来获取基于特定jobId. 该服务的实现可以返回状态、完成百分比或任何其他相关信息,告诉调用者更新过程的当前状态。该方法的实现需要能够报告增量进度(例如报告本地存储中的增量存储),以便做出准确的进度条,否则UI最多只能显示旋转的进度条。
    • 请注意,如果无法实现此类增量报告,则更新过程可能应该使用典型AsyncTask用法,即在后台执行更新并在完成时向用户报告。如果此操作可能需要一段时间,您可以通过Android通知栏或推送通知来实现更新完成。

假设您有获取更新进度的接口,您可以利用AsyncTask onProgressUpdate来报告更新进度。该方法是专门为此设计的。

您的步骤大致如下:

  • 通过一个AsyncTask执行接口更新。由于您的更新是异步发生的,因此此特定任务应该相当快地返回,并报告执行是否成功运行或失败,因为某些异常以及当前正在执行的 jobId
  • 启动另一个 AsyncTask,该任务正在 ping 更新状态并通过 报告进度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)