2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.internal.util.test;
19 import android.content.Context;
20 import android.os.Handler;
21 import android.os.Looper;
22 import android.os.Message;
23 import android.os.Messenger;
24 import android.util.Log;
26 import com.android.internal.util.AsyncChannel;
28 import java.util.HashMap;
32 * Provides an interface for the server side implementation of a bidirectional channel as described
33 * in {@link com.android.internal.util.AsyncChannel}.
35 public class BidirectionalAsyncChannelServer {
37 private static final String TAG = "BidirectionalAsyncChannelServer";
39 // Keeps track of incoming clients, which are identifiable by their messengers.
40 private final Map<Messenger, AsyncChannel> mClients = new HashMap<>();
42 private Messenger mMessenger;
44 public BidirectionalAsyncChannelServer(final Context context, final Looper looper,
45 final Handler messageHandler) {
46 Handler handler = new Handler(looper) {
48 public void handleMessage(Message msg) {
49 AsyncChannel channel = mClients.get(msg.replyTo);
51 case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION:
52 if (channel != null) {
53 Log.d(TAG, "duplicate client connection: " + msg.sendingUid);
54 channel.replyToMessage(msg,
55 AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED,
56 AsyncChannel.STATUS_FULL_CONNECTION_REFUSED_ALREADY_CONNECTED);
58 channel = new AsyncChannel();
59 mClients.put(msg.replyTo, channel);
60 channel.connected(context, this, msg.replyTo);
61 channel.replyToMessage(msg, AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED,
62 AsyncChannel.STATUS_SUCCESSFUL);
65 case AsyncChannel.CMD_CHANNEL_DISCONNECT:
69 case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
70 mClients.remove(msg.replyTo);
74 messageHandler.handleMessage(msg);
79 mMessenger = new Messenger(handler);
82 public Messenger getMessenger() {