1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.lifecycle;
18 
19 import android.app.Service;
20 import android.content.Intent;
21 import android.os.IBinder;
22 
23 import androidx.annotation.CallSuper;
24 import androidx.annotation.Nullable;
25 
26 /**
27  * A Service that is also a {@link LifecycleOwner}.
28  */
29 public class LifecycleService extends Service implements LifecycleOwner {
30 
31     private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
32 
33     @CallSuper
34     @Override
onCreate()35     public void onCreate() {
36         mDispatcher.onServicePreSuperOnCreate();
37         super.onCreate();
38     }
39 
40     @CallSuper
41     @Nullable
42     @Override
onBind(Intent intent)43     public IBinder onBind(Intent intent) {
44         mDispatcher.onServicePreSuperOnBind();
45         return null;
46     }
47 
48     @SuppressWarnings("deprecation")
49     @CallSuper
50     @Override
onStart(Intent intent, int startId)51     public void onStart(Intent intent, int startId) {
52         mDispatcher.onServicePreSuperOnStart();
53         super.onStart(intent, startId);
54     }
55 
56     // this method is added only to annotate it with @CallSuper.
57     // In usual service super.onStartCommand is no-op, but in LifecycleService
58     // it results in mDispatcher.onServicePreSuperOnStart() call, because
59     // super.onStartCommand calls onStart().
60     @CallSuper
61     @Override
onStartCommand(Intent intent, int flags, int startId)62     public int onStartCommand(Intent intent, int flags, int startId) {
63         return super.onStartCommand(intent, flags, startId);
64     }
65 
66     @CallSuper
67     @Override
onDestroy()68     public void onDestroy() {
69         mDispatcher.onServicePreSuperOnDestroy();
70         super.onDestroy();
71     }
72 
73     @Override
getLifecycle()74     public Lifecycle getLifecycle() {
75         return mDispatcher.getLifecycle();
76     }
77 }
78