1package org.robolectric.android.controller;
2
3import static org.robolectric.util.ReflectionHelpers.ClassParameter.from;
4
5import android.app.ActivityThread;
6import android.app.Application;
7import android.app.Service;
8import android.content.Context;
9import android.content.Intent;
10import android.os.IBinder;
11import org.robolectric.RuntimeEnvironment;
12import org.robolectric.util.ReflectionHelpers;
13
14public class ServiceController<T extends Service> extends ComponentController<ServiceController<T>, T> {
15
16  public static <T extends Service> ServiceController<T> of(T service, Intent intent) {
17    ServiceController<T> controller = new ServiceController<>(service, intent);
18    controller.attach();
19    return controller;
20  }
21
22  private ServiceController(T service, Intent intent) {
23    super(service, intent);
24  }
25
26  private ServiceController<T> attach() {
27    if (attached) {
28      return this;
29    }
30
31    ReflectionHelpers.callInstanceMethod(Service.class, component, "attach",
32        from(Context.class, RuntimeEnvironment.application.getBaseContext()),
33        from(ActivityThread.class, null),
34        from(String.class, component.getClass().getSimpleName()),
35        from(IBinder.class, null),
36        from(Application.class, RuntimeEnvironment.application),
37        from(Object.class, null));
38
39    attached = true;
40    return this;
41  }
42
43  public ServiceController<T> bind() {
44    invokeWhilePaused("onBind", from(Intent.class, getIntent()));
45    return this;
46  }
47
48  @Override public ServiceController<T> create() {
49    invokeWhilePaused("onCreate");
50    return this;
51  }
52
53  @Override public ServiceController<T> destroy() {
54    invokeWhilePaused("onDestroy");
55    return this;
56  }
57
58  public ServiceController<T> rebind() {
59    invokeWhilePaused("onRebind", from(Intent.class, getIntent()));
60    return this;
61  }
62
63  public ServiceController<T> startCommand(int flags, int startId) {
64    invokeWhilePaused("onStartCommand", from(Intent.class, getIntent()), from(int.class, flags), from(int.class, startId));
65    return this;
66  }
67
68  public ServiceController<T> unbind() {
69    invokeWhilePaused("onUnbind", from(Intent.class, getIntent()));
70    return this;
71  }
72
73  /**
74   * @deprecated Use the appropriate builder in {@link org.robolectric.Robolectric} instead.
75   *
76   * This method will be removed in Robolectric 3.6.
77   */
78  @Deprecated
79  public ServiceController<T> withIntent(Intent intent) {
80    this.intent = intent;
81    return this;
82  }
83}
84