From b7ed883aecefa992a37f0a5202c28a7d6856b67c Mon Sep 17 00:00:00 2001 From: Eric Anderson Date: Mon, 20 Jun 2016 14:35:21 -0700 Subject: [PATCH] core: Avoid loading ManagedChannelProvider from NameResolverProvider Not all users are triggering the loading of ManagedChannelProvider, so avoid the unnecessary loading. Also, since class initialization is involved, exception handling tends to get strange and hard to diagnose issues. --- core/src/main/java/io/grpc/NameResolverProvider.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/io/grpc/NameResolverProvider.java b/core/src/main/java/io/grpc/NameResolverProvider.java index ce724548ea..26fb9554a7 100644 --- a/core/src/main/java/io/grpc/NameResolverProvider.java +++ b/core/src/main/java/io/grpc/NameResolverProvider.java @@ -98,7 +98,7 @@ public abstract class NameResolverProvider extends NameResolver.Factory { } private static ClassLoader getCorrectClassLoader() { - if (ManagedChannelProvider.isAndroid()) { + if (isAndroid()) { // When android:sharedUserId or android:process is used, Android will setup a dummy // ClassLoader for the thread context (http://stackoverflow.com/questions/13407006), // instead of letting users to manually set context class loader, we choose the @@ -108,6 +108,16 @@ public abstract class NameResolverProvider extends NameResolver.Factory { return Thread.currentThread().getContextClassLoader(); } + private static boolean isAndroid() { + try { + Class.forName("android.app.Application", /*initialize=*/ false, null); + return true; + } catch (Exception e) { + // If Application isn't loaded, it might as well not be Android. + return false; + } + } + /** * Whether this provider is available for use, taking the current environment into consideration. * If {@code false}, no other methods are safe to be called.