summaryrefslogtreecommitdiff
path: root/core/java/com/android/internal/util/ObservableServiceConnection.java
blob: 45256fd26cba69904e5d0a9d70e472cb2b379d0a (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
/*
 * Copyright (C) 2022 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.android.internal.util;

import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.CallbackRegistry.NotifierCallback;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.concurrent.Executor;

/**
 * {@link ObservableServiceConnection} is a concrete implementation of {@link ServiceConnection}
 * that enables monitoring the status of a binder connection. It also aides in automatically
 * converting a proxy into an internal wrapper type.
 *
 * @param <T> The type of the wrapper over the resulting service.
 */
public class ObservableServiceConnection<T> implements ServiceConnection {
    /**
     * An interface for converting the service proxy into a given internal wrapper type.
     *
     * @param <T> The type of the wrapper over the resulting service.
     */
    public interface ServiceTransformer<T> {
        /**
         * Called to convert the service proxy to the wrapper type.
         *
         * @param service The service proxy to create the wrapper type from.
         * @return The wrapper type.
         */
        T convert(IBinder service);
    }

    /**
     * An interface for listening to the connection status.
     *
     * @param <T> The wrapper type.
     */
    public interface Callback<T> {
        /**
         * Invoked when the service has been successfully connected to.
         *
         * @param connection The {@link ObservableServiceConnection} instance that is now connected
         * @param service    The service proxy converted into the typed wrapper.
         */
        void onConnected(ObservableServiceConnection<T> connection, T service);

        /**
         * Invoked when the service has been disconnected.
         *
         * @param connection The {@link ObservableServiceConnection} that is now disconnected.
         * @param reason     The reason for the disconnection.
         */
        void onDisconnected(ObservableServiceConnection<T> connection,
                @DisconnectReason int reason);
    }

    /**
     * Default state, service has not yet disconnected.
     */
    public static final int DISCONNECT_REASON_NONE = 0;
    /**
     * Disconnection was due to the resulting binding being {@code null}.
     */
    public static final int DISCONNECT_REASON_NULL_BINDING = 1;
    /**
     * Disconnection was due to the remote end disconnecting.
     */
    public static final int DISCONNECT_REASON_DISCONNECTED = 2;
    /**
     * Disconnection due to the binder dying.
     */
    public static final int DISCONNECT_REASON_BINDING_DIED = 3;
    /**
     * Disconnection from an explicit unbinding.
     */
    public static final int DISCONNECT_REASON_UNBIND = 4;

    @Retention(RetentionPolicy.SOURCE)
    @IntDef({
            DISCONNECT_REASON_NONE,
            DISCONNECT_REASON_NULL_BINDING,
            DISCONNECT_REASON_DISCONNECTED,
            DISCONNECT_REASON_BINDING_DIED,
            DISCONNECT_REASON_UNBIND
    })
    public @interface DisconnectReason {
    }

    private final Object mLock = new Object();
    private final Context mContext;
    private final Executor mExecutor;
    private final ServiceTransformer<T> mTransformer;
    private final Intent mServiceIntent;
    private final int mFlags;

    @GuardedBy("mLock")
    private T mService;
    @GuardedBy("mLock")
    private boolean mBoundCalled = false;
    @GuardedBy("mLock")
    private int mLastDisconnectReason = DISCONNECT_REASON_NONE;

    private final CallbackRegistry<Callback<T>, ObservableServiceConnection<T>, T>
            mCallbackRegistry = new CallbackRegistry<>(
            new NotifierCallback<Callback<T>, ObservableServiceConnection<T>, T>() {
                    @Override
                    public void onNotifyCallback(Callback<T> callback,
                            ObservableServiceConnection<T> sender,
                            int disconnectReason, T service) {
                        mExecutor.execute(() -> {
                            synchronized (mLock) {
                                if (service != null) {
                                    callback.onConnected(sender, service);
                                } else if (mLastDisconnectReason != DISCONNECT_REASON_NONE) {
                                    callback.onDisconnected(sender, disconnectReason);
                                }
                            }
                        });
                    }
                });

    /**
     * Default constructor for {@link ObservableServiceConnection}.
     *
     * @param context     The context from which the service will be bound with.
     * @param executor    The executor for connection callbacks to be delivered on
     * @param transformer A {@link ObservableServiceConnection.ServiceTransformer} for transforming
     *                    the resulting service into a desired type.
     */
    public ObservableServiceConnection(@NonNull Context context,
            @NonNull @CallbackExecutor Executor executor,
            @NonNull ServiceTransformer<T> transformer,
            Intent serviceIntent,
            int flags) {
        mContext = context;
        mExecutor = executor;
        mTransformer = transformer;
        mServiceIntent = serviceIntent;
        mFlags = flags;
    }

    /**
     * Executes code on the executor specified at construction.
     */
    public void execute(Runnable runnable) {
        mExecutor.execute(runnable);
    }

    /**
     * Initiate binding to the service.
     *
     * @return {@code true} if initiating binding succeed, {@code false} if the binding failed or
     * if this service is already bound. Regardless of the return value, you should later call
     * {@link #unbind()} to release the connection.
     */
    public boolean bind() {
        synchronized (mLock) {
            if (mBoundCalled) {
                return false;
            }
            final boolean bindResult =
                    mContext.bindService(mServiceIntent, mFlags, mExecutor, this);
            mBoundCalled = true;
            return bindResult;
        }
    }

    /**
     * Disconnect from the service if bound.
     */
    public void unbind() {
        onDisconnected(DISCONNECT_REASON_UNBIND);
    }

    /**
     * Adds a callback for receiving connection updates.
     *
     * @param callback The {@link Callback} to receive future updates.
     */
    public void addCallback(Callback<T> callback) {
        mCallbackRegistry.add(callback);
        mExecutor.execute(() -> {
            synchronized (mLock) {
                if (mService != null) {
                    callback.onConnected(this, mService);
                } else if (mLastDisconnectReason != DISCONNECT_REASON_NONE) {
                    callback.onDisconnected(this, mLastDisconnectReason);
                }
            }
        });
    }

    /**
     * Removes previously added callback from receiving future connection updates.
     *
     * @param callback The {@link Callback} to be removed.
     */
    public void removeCallback(Callback<T> callback) {
        synchronized (mLock) {
            mCallbackRegistry.remove(callback);
        }
    }

    private void onDisconnected(@DisconnectReason int reason) {
        synchronized (mLock) {
            if (!mBoundCalled) {
                return;
            }
            mBoundCalled = false;
            mLastDisconnectReason = reason;
            mContext.unbindService(this);
            mService = null;
            mCallbackRegistry.notifyCallbacks(this, reason, null);
        }
    }

    @Override
    public final void onServiceConnected(ComponentName name, IBinder service) {
        synchronized (mLock) {
            mService = mTransformer.convert(service);
            mLastDisconnectReason = DISCONNECT_REASON_NONE;
            mCallbackRegistry.notifyCallbacks(this, mLastDisconnectReason, mService);
        }
    }

    @Override
    public final void onServiceDisconnected(ComponentName name) {
        onDisconnected(DISCONNECT_REASON_DISCONNECTED);
    }

    @Override
    public final void onBindingDied(ComponentName name) {
        onDisconnected(DISCONNECT_REASON_BINDING_DIED);
    }

    @Override
    public final void onNullBinding(ComponentName name) {
        onDisconnected(DISCONNECT_REASON_NULL_BINDING);
    }
}