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 * 30 * @param <EventType> type of event to be handled 31 * @hide 32 */ 33 public abstract class SingleMessageHandler<EventType> implements Callback { 34 private final int mHandledMessageWhat; 35 private final Handler mHandler; 36 SingleMessageHandler(Looper looper, int handledMessage)37 public SingleMessageHandler(Looper looper, int handledMessage) { 38 mHandledMessageWhat = handledMessage; 39 mHandler = new Handler(looper, this); 40 } 41 SingleMessageHandler(Handler handler, int handledMessage)42 public SingleMessageHandler(Handler handler, int handledMessage) { 43 this(handler.getLooper(), handledMessage); 44 } 45 handleEvent(EventType event)46 protected abstract void handleEvent(EventType event); 47 48 @Override handleMessage(Message msg)49 public boolean handleMessage(Message msg) { 50 if (msg.what == mHandledMessageWhat) { 51 List<EventType> events = (List<EventType>) msg.obj; 52 events.forEach(new Consumer<EventType>() { 53 @Override 54 public void accept(EventType event) { 55 handleEvent(event); 56 } 57 }); 58 } 59 60 return true; 61 } 62 63 /** Send the events passsed as parameter */ sendEvents(List<EventType> events)64 public void sendEvents(List<EventType> events) { 65 mHandler.sendMessage(mHandler.obtainMessage(mHandledMessageWhat, events)); 66 } 67 68 } 69