summaryrefslogtreecommitdiff
path: root/main/java/com/google/android/setupcompat/internal/SetupCompatServiceProvider.java
blob: 2043a81538d377a908bf39a686a959d8f7cab11a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.setupcompat.internal;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import android.util.Log;
import com.google.android.setupcompat.ISetupCompatService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;

/**
 * This class provides an instance of {@link ISetupCompatService}. It keeps track of the connection
 * state and reconnects if necessary.
 */
public class SetupCompatServiceProvider {

  /**
   * Returns an instance of {@link ISetupCompatService} if one already exists. If not, attempts to
   * rebind if the current state allows such an operation and waits until {@code waitTime} for
   * receiving the stub reference via {@link ServiceConnection#onServiceConnected(ComponentName,
   * IBinder)}.
   *
   * @throws IllegalStateException if called from the main thread since this is a blocking
   *     operation.
   * @throws TimeoutException if timed out waiting for {@code waitTime}.
   */
  public static ISetupCompatService get(Context context, long waitTime, @NonNull TimeUnit timeUnit)
      throws TimeoutException, InterruptedException {
    return getInstance(context).getService(waitTime, timeUnit);
  }

  @VisibleForTesting
  public ISetupCompatService getService(long timeout, TimeUnit timeUnit)
      throws TimeoutException, InterruptedException {
    Preconditions.checkState(
        disableLooperCheckForTesting || Looper.getMainLooper() != Looper.myLooper(),
        "getService blocks and should not be called from the main thread.");
    ServiceContext serviceContext = getCurrentServiceState();
    switch (serviceContext.state) {
      case CONNECTED:
        return serviceContext.compatService;

      case SERVICE_NOT_USABLE:
      case BIND_FAILED:
        // End states, no valid connection can be obtained ever.
        return null;

      case DISCONNECTED:
      case BINDING:
        return waitForConnection(timeout, timeUnit);

      case REBIND_REQUIRED:
        requestServiceBind();
        return waitForConnection(timeout, timeUnit);

      case NOT_STARTED:
        throw new IllegalStateException(
            "NOT_STARTED state only possible before instance is created.");
    }
    throw new IllegalStateException("Unknown state = " + serviceContext.state);
  }

  private ISetupCompatService waitForConnection(long timeout, TimeUnit timeUnit)
      throws TimeoutException, InterruptedException {
    ServiceContext currentServiceState = getCurrentServiceState();
    if (currentServiceState.state == State.CONNECTED) {
      return currentServiceState.compatService;
    }

    CountDownLatch connectedStateLatch = getConnectedCondition();
    Log.i(TAG, "Waiting for service to get connected");
    boolean stateChanged = connectedStateLatch.await(timeout, timeUnit);
    if (!stateChanged) {
      // Even though documentation states that disconnected service should connect again,
      // requesting rebind reduces the wait time to acquire a new connection.
      requestServiceBind();
      throw new TimeoutException(
          String.format("Failed to acquire connection after [%s %s]", timeout, timeUnit));
    }
    currentServiceState = getCurrentServiceState();
    if (Log.isLoggable(TAG, Log.INFO)) {
      Log.i(
          TAG,
          String.format(
              "Finished waiting for service to get connected. Current state = %s",
              currentServiceState.state));
    }
    return currentServiceState.compatService;
  }

  /**
   * This method is being overwritten by {@link SetupCompatServiceProviderTest} for injecting an
   * instance of {@link CountDownLatch}.
   */
  @VisibleForTesting
  protected CountDownLatch createCountDownLatch() {
    return new CountDownLatch(1);
  }

  private synchronized void requestServiceBind() {
    ServiceContext currentServiceState = getCurrentServiceState();
    if (currentServiceState.state == State.CONNECTED) {
      Log.i(TAG, "Refusing to rebind since current state is already connected");
      return;
    }
    if (currentServiceState.state != State.NOT_STARTED) {
      Log.i(TAG, "Unbinding existing service connection.");
      context.unbindService(serviceConnection);
    }

    boolean bindAllowed;
    try {
      bindAllowed =
          context.bindService(COMPAT_SERVICE_INTENT, serviceConnection, Context.BIND_AUTO_CREATE);
    } catch (SecurityException e) {
      Log.e(TAG, "Unable to bind to compat service", e);
      bindAllowed = false;
    }

    if (bindAllowed) {
      // Robolectric calls ServiceConnection#onServiceConnected inline during Context#bindService.
      // This check prevents us from overriding connected state which usually arrives much later
      // in the normal world
      if (getCurrentState() != State.CONNECTED) {
        swapServiceContextAndNotify(new ServiceContext(State.BINDING));
        Log.i(TAG, "Context#bindService went through, now waiting for service connection");
      }
    } else {
      // SetupWizard is not installed/calling app does not have permissions to bind.
      swapServiceContextAndNotify(new ServiceContext(State.BIND_FAILED));
      Log.e(TAG, "Context#bindService did not succeed.");
    }
  }

  @VisibleForTesting
  static final Intent COMPAT_SERVICE_INTENT =
      new Intent()
          .setPackage("com.google.android.setupwizard")
          .setAction("com.google.android.setupcompat.SetupCompatService.BIND");

  @VisibleForTesting
  State getCurrentState() {
    return serviceContext.state;
  }

  private synchronized ServiceContext getCurrentServiceState() {
    return serviceContext;
  }

  private void swapServiceContextAndNotify(ServiceContext latestServiceContext) {
    if (Log.isLoggable(TAG, Log.INFO)) {
      Log.i(
          TAG,
          String.format(
              "State changed: %s -> %s", serviceContext.state, latestServiceContext.state));
    }
    serviceContext = latestServiceContext;
    CountDownLatch countDownLatch = getAndClearConnectedCondition();
    if (countDownLatch != null) {
      countDownLatch.countDown();
    }
  }

  private CountDownLatch getAndClearConnectedCondition() {
    return connectedConditionRef.getAndSet(/* newValue= */ null);
  }

  /**
   * Cannot use {@link AtomicReference#updateAndGet(UnaryOperator)} to fix null reference since the
   * library needs to be compatible with legacy android devices.
   */
  private CountDownLatch getConnectedCondition() {
    CountDownLatch countDownLatch;
    // Loop until either count down latch is found or successfully able to update atomic reference.
    do {
      countDownLatch = connectedConditionRef.get();
      if (countDownLatch != null) {
        return countDownLatch;
      }
      countDownLatch = createCountDownLatch();
    } while (!connectedConditionRef.compareAndSet(/* expect= */ null, countDownLatch));
    return countDownLatch;
  }

  @VisibleForTesting
  SetupCompatServiceProvider(Context context) {
    this.context = context.getApplicationContext();
  }

  @VisibleForTesting
  final ServiceConnection serviceConnection =
      new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder binder) {
          State state = State.CONNECTED;
          if (binder == null) {
            state = State.DISCONNECTED;
            Log.w(TAG, "Binder is null when onServiceConnected was called!");
          }
          swapServiceContextAndNotify(
              new ServiceContext(state, ISetupCompatService.Stub.asInterface(binder)));
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
          swapServiceContextAndNotify(new ServiceContext(State.DISCONNECTED));
        }

        @Override
        public void onBindingDied(ComponentName name) {
          swapServiceContextAndNotify(new ServiceContext(State.REBIND_REQUIRED));
        }

        @Override
        public void onNullBinding(ComponentName name) {
          swapServiceContextAndNotify(new ServiceContext(State.SERVICE_NOT_USABLE));
        }
      };

  private volatile ServiceContext serviceContext = new ServiceContext(State.NOT_STARTED);
  private final Context context;
  private final AtomicReference<CountDownLatch> connectedConditionRef = new AtomicReference<>();

  @VisibleForTesting
  enum State {
    /** Initial state of the service instance is completely created. */
    NOT_STARTED,

    /**
     * Attempt to call {@link Context#bindService(Intent, ServiceConnection, int)} failed because,
     * either Setupwizard is not installed or the app does not have permission to bind. This is an
     * unrecoverable situation.
     */
    BIND_FAILED,

    /**
     * Call to bind with the service went through, now waiting for {@link
     * ServiceConnection#onServiceConnected(ComponentName, IBinder)}.
     */
    BINDING,

    /** Provider is connected to the service and can call the API(s). */
    CONNECTED,

    /**
     * Not connected since provider received the call {@link
     * ServiceConnection#onServiceDisconnected(ComponentName)}, and waiting for {@link
     * ServiceConnection#onServiceConnected(ComponentName, IBinder)}.
     */
    DISCONNECTED,

    /**
     * Similar to {@link #BIND_FAILED}, the bind call went through but we received a "null" binding
     * via {@link ServiceConnection#onNullBinding(ComponentName)}. This is an unrecoverable
     * situation.
     */
    SERVICE_NOT_USABLE,

    /**
     * The provider has requested rebind via {@link Context#bindService(Intent, ServiceConnection,
     * int)} and is waiting for a service connection.
     */
    REBIND_REQUIRED
  }

  private static final class ServiceContext {
    final State state;
    @Nullable final ISetupCompatService compatService;

    private ServiceContext(State state, @Nullable ISetupCompatService compatService) {
      this.state = state;
      this.compatService = compatService;
      if (state == State.CONNECTED) {
        Preconditions.checkNotNull(
            compatService, "CompatService cannot be null when state is connected");
      }
    }

    private ServiceContext(State state) {
      this(state, /* compatService= */ null);
    }
  }

  @VisibleForTesting
  static SetupCompatServiceProvider getInstance(@NonNull Context context) {
    Preconditions.checkNotNull(context, "Context object cannot be null.");
    SetupCompatServiceProvider result = instance;
    if (result == null) {
      synchronized (SetupCompatServiceProvider.class) {
        result = instance;
        if (result == null) {
          instance = result = new SetupCompatServiceProvider(context.getApplicationContext());
          instance.requestServiceBind();
        }
      }
    }
    return result;
  }

  @VisibleForTesting
  public static void setInstanceForTesting(SetupCompatServiceProvider testInstance) {
    instance = testInstance;
  }

  @VisibleForTesting static boolean disableLooperCheckForTesting = false;

  // The instance is coming from Application context which alive during the application activate and
  // it's not depend on the activities life cycle, so we can avoid memory leak. However linter
  // cannot distinguish Application context or activity context, so we add @SuppressLint to avoid
  // lint error.
  @SuppressLint("StaticFieldLeak")
  private static volatile SetupCompatServiceProvider instance;

  private static final String TAG = "SucServiceProvider";
}