【问题标题】:How to cast LifecycleOwner on Service class?如何在服务类上投射 LifecycleOwner?
【发布时间】:2019-07-27 06:52:23
【问题描述】:

我想使用服务类中的 livedata 选择房间数据库中的数据。 LifecycleOwner 观察时如何施放?

repositoryDatabase.getTimeline().observe(this, timelineList -> {
    if (timelineList != null && timelineList.size() >= 10) {
        JSONArray arrayTimeline = new JSONArray();
        for (TimelineEntity timeline : timelineList) {
            JSONObject objectTimeline = new JSONObject();
            try {
                objectTimeline.put("doku", timeline.getIdDokumen());
                objectTimeline.put("entrydate", timeline.getEntryDate());
                objectTimeline.put("lat", timeline.getLat());
                objectTimeline.put("lng", timeline.getLng());

                arrayTimeline.put(objectTimeline);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        onUpdateLocation(arrayTimeline.toString());
    }
});

【问题讨论】:

    标签: java android android-room android-livedata


    【解决方案1】:

    你可以像这样使用LifecycleService

    将此依赖项添加到您的 app/build.gradle 文件中:

    dependencies {
        implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
    }
    

    通过LifecycleService 扩展您的服务:

    class MyService extends LifecycleService {
    
        ...
    }
    

    之后您将能够观察到您的LiveData

    【讨论】:

      【解决方案2】:

      将此依赖项添加到您的 app/build.gradle 文件中:

      implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
      

      androidx.lifecycle release page中所述

      版本 2.2.0 ~~ 2020 年 1 月 22 日 ~~ 自 2.1.0 以来的重要更改

      生命周期扩展工件弃用:由于 ViewModelProviders.of() 的上述弃用,此版本标志着生命周期扩展中最后一个 API 的弃用,现在应该认为该工件已被完全弃用。我们强烈建议根据您需要的特定生命周期工件(例如,如果您使用 LifecycleService,则生命周期服务和生命周期流程,如果您使用 ProcessLifecycleOwner)而不是生命周期扩展,因为未来不会有 2.3.0 版本生命周期扩展。

      【讨论】:

        【解决方案3】:

        添加依赖 implementation "androidx.lifecycle:lifecycle-service:2.2.0"

        如果你已经扩展了service(),你应该删除它并扩展LifecycleService()

        您的服务现在应该如下所示:

        class MyService() : LifecycleService() {
            //CODE
        }
        

        【讨论】:

          猜你喜欢
          • 2021-09-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-17
          • 2016-10-19
          • 2020-09-23
          • 2023-02-03
          • 1970-01-01
          相关资源
          最近更新 更多