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