Yan Zhu | 285718d | 2019-05-29 15:40:40 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2019 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 | package com.google.android.car.multidisplaytest.ime; |
| 17 | |
| 18 | import android.os.Handler; |
| 19 | import android.util.Log; |
| 20 | import android.widget.TextView; |
| 21 | |
| 22 | import java.text.SimpleDateFormat; |
| 23 | import java.util.ArrayList; |
| 24 | import java.util.Date; |
| 25 | |
| 26 | /** |
| 27 | * Copied from GarageModeTestApp |
| 28 | * Use Handler to send and process messages in a queue |
| 29 | * Potentially use for multi-thread |
| 30 | */ |
| 31 | public final class Watchdog { |
| 32 | private static final String TAG = Watchdog.class.getSimpleName(); |
| 33 | // wait before trying to get new message from the queue and post it |
| 34 | private static final Integer DELAY = 500; // in millisecond |
| 35 | private static final Integer MAXQSIZE = 10000; |
| 36 | |
| 37 | private final TextView mView; |
| 38 | private final ArrayList<String> mEvents; |
| 39 | |
| 40 | private Handler mWatchdogHandler; |
| 41 | private Runnable mRefreshLoop; |
| 42 | |
| 43 | Watchdog(TextView view) { |
| 44 | mView = view; |
| 45 | mEvents = new ArrayList<>(); |
| 46 | } |
| 47 | |
| 48 | public void logEvent(String s) { |
| 49 | Date date = new Date(); |
| 50 | SimpleDateFormat dateFormat = new SimpleDateFormat("[yyyy-MM-dd hh:mm:ss]"); |
| 51 | mEvents.add(0, dateFormat.format(date) + " " + s); |
| 52 | |
| 53 | if (mEvents.size() > MAXQSIZE) { |
| 54 | mEvents.remove(mEvents.size() - 1); |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | public synchronized void refresh() { |
| 59 | mView.setText(String.join("\n", mEvents)); |
| 60 | } |
| 61 | |
| 62 | public void start() { |
| 63 | Log.d(TAG, "Starting Watchdog"); |
| 64 | mEvents.clear(); |
| 65 | mWatchdogHandler = new Handler(); |
| 66 | mRefreshLoop = () -> { |
| 67 | refresh(); |
| 68 | mWatchdogHandler.postDelayed(mRefreshLoop, DELAY); |
| 69 | }; |
| 70 | mWatchdogHandler.postDelayed(mRefreshLoop, DELAY); |
| 71 | } |
| 72 | |
| 73 | public void stop() { |
| 74 | Log.d(TAG, "Stopping Watchdog"); |
| 75 | mWatchdogHandler.removeCallbacks(mRefreshLoop); |
| 76 | mWatchdogHandler = null; |
| 77 | mRefreshLoop = null; |
| 78 | } |
| 79 | } |