BadGuy
BadGuy

Reputation: 163

How to cast LifecycleOwner on Service class?

I want to select data on room database with livedata from service class. How to cast the LifecycleOwner when observe it?

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());
    }
});

Upvotes: 15

Views: 8998

Answers (3)

Sourav
Sourav

Reputation: 402

add dependency implementation "androidx.lifecycle:lifecycle-service:2.2.0"

if you have extended service() already you should remove it and extend LifecycleService()

Your service should look like this now:

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

Upvotes: 1

Nur Ilyas
Nur Ilyas

Reputation: 121

Add this dependency to your app/build.gradle file:

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

As mentioned in the androidx.lifecycle release page

Version 2.2.0 ~~ January 22, 2020 ~~ Important changes since 2.1.0

lifecycle-extensions Artifact Deprecation: With the above deprecation of ViewModelProviders.of(), this release marks the deprecation of the last API in lifecycle-extensions and this artifact should now be considered deprecated in its entirety. We strongly recommend depending on the specific Lifecycle artifacts you need (such as lifecycle-service if you’re using LifecycleService and lifecycle-process if you’re using ProcessLifecycleOwner) rather than lifecycle-extensions as there will not be a future 2.3.0 release of lifecycle-extensions.

Upvotes: 6

Birju Vachhani
Birju Vachhani

Reputation: 6373

You can use LifecycleService like this:

Add this dependency to your app/build.gradle file:

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

Extend your service with LifecycleService:

class MyService extends LifecycleService {

    ...
}

After that you will be able to observe your LiveData.

Upvotes: 23

Related Questions