From b2a6964fc21d3c18eff087153014961b9b430619 Mon Sep 17 00:00:00 2001 From: chiachangwang Date: Thu, 1 Dec 2022 01:11:26 +0000 Subject: [PATCH] Add withCleanCallingIdentity with Supplier to module utils Binder#withCleanCallingIdentity with Supplier is a very useful utility but it's not public. Thus, make one in the connectivity module utils. Bug: 255231779 Test: m ; adb shell dumpsys connectivity Change-Id: I029a34a96b1107111a605b91a54c8fdb071e9fc0 --- .../android/net/module/util/BinderUtils.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/staticlibs/framework/com/android/net/module/util/BinderUtils.java b/staticlibs/framework/com/android/net/module/util/BinderUtils.java index eb695d1f9d..e4d14ea8d6 100644 --- a/staticlibs/framework/com/android/net/module/util/BinderUtils.java +++ b/staticlibs/framework/com/android/net/module/util/BinderUtils.java @@ -19,6 +19,8 @@ package com.android.net.module.util; import android.annotation.NonNull; import android.os.Binder; +import java.util.function.Supplier; + /** * Collection of utilities for {@link Binder} and related classes. * @hide @@ -56,4 +58,39 @@ public class BinderUtils { /** @see java.lang.Runnable */ void run() throws T; } + + /** + * Convenience method for running the provided action enclosed in + * {@link Binder#clearCallingIdentity}/{@link Binder#restoreCallingIdentity} returning the + * result. + * + *

Any exception thrown by the given action will be caught and rethrown after + * the call to {@link Binder#restoreCallingIdentity}. + * + * Note that this is copied from Binder#withCleanCallingIdentity with minor changes + * since it is not public. + * + * @hide + */ + public static final T withCleanCallingIdentity( + @NonNull ThrowingSupplier action) throws E { + final long callingIdentity = Binder.clearCallingIdentity(); + try { + return action.get(); + } finally { + Binder.restoreCallingIdentity(callingIdentity); + } + } + + /** + * An equivalent of {@link Supplier} + * + * @param The class which is declared to be returned. + * @param The exception class which is declared to be thrown. + */ + @FunctionalInterface + public interface ThrowingSupplier { + /** @see java.util.function.Supplier */ + T get() throws E; + } }