安卓 fragment : which life cycle method to use for web service call

标签 android android-fragments

我正在开发一个涉及多个 fragment 的应用程序。 在每个 fragment 中,我都必须调用网络服务来获取数据。

目前我正在从 Fragment 的 onCreateView() 方法调用网络服务。问题是,每当 Web 服务调用正在进行时,如果设备方向发生变化,就会开始调用新的 Web 服务调用。

我认为这可能是因为 onCreateView() 方法在配置更改时被调用。

我该如何解决这个问题。以及我应该使用哪种生命周期方法来调用 Web 服务,以便它只会被调用一次

最佳答案

我已经通过以下解决方法解决了这个问题

  1. 为每个网络服务调用方法创建一个操作标识符。例如。例如登录调用的“身份验证”

  2. 创建一个 ArrayList 对象,比如 currentTasks

    ArrayList<String> currentTasks = new ArrayList<String>();
    
  3. 在我调用网络服务的每个方法中,检查相应方法的操作标识符是否已存在于 ArrayList 中。如果没有则开始操作。

    String operationId = "Authentication";
    if(currentTasks.indexOf(operationId) == -1)
    {
      <do web service call operation here>
       currentTasks.add(operationId);
    }
    
  4. 接收上述操作响应的方法,从ArrayList中移除操作标识符

     if(currentTasks.indexOf("Authentication") != -1){
        currentTasks.remove("Authentication");
     }
    

这将确保调用不会转到当前正在进行的网络方法。

我知道这不是实现它的最佳方法,也可能不是可遵循的最佳实践,但目前这对我有用。

关于安卓 fragment : which life cycle method to use for web service call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852917/

相关文章:

java - 显示或隐藏 fragment 菜单

android - 如何使 DialogFragment 包装其内容并同时将 View 对齐到底部?

java - fragment 没有每次都刷新/调用

android - 回收站 View : Go to a position not scroll to

java - Android 类的结构/命名

android - CSS Flex 支持 Android WebView 和 iOS UIWebView

java - 处理android中的后退按钮操作

android - MapFragment 在 getMapAsync(this) 方法中导致 NullPointerException

android - 如何为 RecyclerView 添加 FooterView

android - 在 react native 应用程序中启用/禁用 Firebase 推送通知