1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 package com.android.car.internal; 18 19 import android.os.Handler; 20 import android.os.Handler.Callback; 21 import android.os.Looper; 22 import android.os.Message; 23 24 import java.util.List; 25 import java.util.function.Consumer; 26 27 /** 28 * Handles call back into clients for Car managers. 29 * @hide 30 */ 31 public abstract class SingleMessageHandler<EventType> implements Callback { 32 private final int mHandledMessageWhat; 33 private final Handler mHandler; 34 SingleMessageHandler(Looper looper, int handledMessage)35 public SingleMessageHandler(Looper looper, int handledMessage) { 36 mHandledMessageWhat = handledMessage; 37 mHandler = new Handler(looper, this); 38 } 39 SingleMessageHandler(Handler handler, int handledMessage)40 public SingleMessageHandler(Handler handler, int handledMessage) { 41 this(handler.getLooper(), handledMessage); 42 } 43 handleEvent(EventType event)44 protected abstract void handleEvent(EventType event); 45 46 @Override handleMessage(Message msg)47 public boolean handleMessage(Message msg) { 48 if (msg.what == mHandledMessageWhat) { 49 List<EventType> events = (List<EventType>) msg.obj; 50 events.forEach(new Consumer<EventType>() { 51 @Override 52 public void accept(EventType event) { 53 handleEvent(event); 54 } 55 }); 56 } 57 58 return true; 59 } 60 sendEvents(List<EventType> events)61 public void sendEvents(List<EventType> events) { 62 mHandler.sendMessage(mHandler.obtainMessage(mHandledMessageWhat, events)); 63 } 64 65 } 66