blob: 56c52bfde3b3b900ac5c6f8c87555a0478bc24d0 [file] [log] [blame]
Brad Ebinger4fb372f2016-10-05 15:47:28 -07001/*
2 * Copyright (C) 2016 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
17package android.telecom.Logging;
18
19import android.telecom.Log;
20
21/**
22 * Encapsulates session logging in a Runnable to reduce code duplication when continuing subsessions
23 * in a handler/thread.
24 * @hide
25 */
26public abstract class Runnable {
27
28 private Session mSubsession;
29 private final String mSubsessionName;
30 private final Object mLock = new Object();
31 private final java.lang.Runnable mRunnable = new java.lang.Runnable() {
32 @Override
33 public void run() {
34 synchronized (mLock) {
35 try {
36 Log.continueSession(mSubsession, mSubsessionName);
37 loggedRun();
38 } finally {
39 if (mSubsession != null) {
40 Log.endSession();
41 mSubsession = null;
42 }
43 }
44 }
45 }
46 };
47
48 public Runnable(String subsessionName) {
49 mSubsessionName = subsessionName;
50 }
51
52 /**
53 * Return the runnable that will be canceled in the handler queue.
54 * @return Runnable object to cancel.
55 */
56 public final java.lang.Runnable getRunnableToCancel() {
57 return mRunnable;
58 }
59
60 /**
61 * Creates a Runnable and a logging subsession that can be used in a handler/thread. Be sure to
62 * call cancel() if this session is never going to be run (removed from a handler queue, for
63 * for example).
64 * @return A Java Runnable that can be used in a handler queue or thread.
65 */
66 public java.lang.Runnable prepare() {
67 cancel();
68 mSubsession = Log.createSubsession();
69 return mRunnable;
70 }
71
72 /**
73 * This method is used to clean up the active session if the Runnable gets removed from a
74 * handler and is never run.
75 */
76 public void cancel() {
77 synchronized (mLock) {
78 Log.cancelSubsession(mSubsession);
79 mSubsession = null;
80 }
81 }
82
83 /**
84 * The method that will be run in the handler/thread.
85 */
86 abstract public void loggedRun();
87
88}