|
| 1 | +/* |
| 2 | + * Copyright 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 | + |
| 17 | +package com.example.glass.camera2sample; |
| 18 | + |
| 19 | +import android.os.Handler; |
| 20 | +import android.os.HandlerThread; |
| 21 | +import android.util.Log; |
| 22 | + |
| 23 | +/** |
| 24 | + * Helper class responsible for handling the background thread. |
| 25 | + */ |
| 26 | +public class BackgroundThreadHandler { |
| 27 | + |
| 28 | + private static final String TAG = BackgroundThreadHandler.class.getSimpleName(); |
| 29 | + |
| 30 | + private final String threadName; |
| 31 | + private HandlerThread handlerThread; |
| 32 | + private Handler handler; |
| 33 | + |
| 34 | + /** |
| 35 | + * Constructor of this class needs a background thread name to be passed by an argument. |
| 36 | + * |
| 37 | + * @param threadName of the background thread to handle. |
| 38 | + */ |
| 39 | + public BackgroundThreadHandler(String threadName) { |
| 40 | + this.threadName = threadName; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Starts a background thread and its {@link Handler}. |
| 45 | + */ |
| 46 | + public void startBackgroundThread() { |
| 47 | + Log.d(TAG, "Starting thread " + threadName); |
| 48 | + handlerThread = new HandlerThread(threadName); |
| 49 | + handlerThread.start(); |
| 50 | + handler = new Handler(handlerThread.getLooper()); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Stops the background thread and its {@link Handler}. |
| 55 | + */ |
| 56 | + public void stopBackgroundThread() { |
| 57 | + Log.d(TAG, "Stopping thread " + threadName); |
| 58 | + handlerThread.quitSafely(); |
| 59 | + try { |
| 60 | + handlerThread.join(); |
| 61 | + handlerThread = null; |
| 62 | + handler = null; |
| 63 | + } catch (InterruptedException e) { |
| 64 | + Log.e(TAG, "Stopping thread " + threadName + " failed", e); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Returns {@link Handler} using the background thread. |
| 70 | + */ |
| 71 | + public Handler getHandler() { |
| 72 | + return handler; |
| 73 | + } |
| 74 | +} |
0 commit comments