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.
This commit is contained in:
Eric Anderson 2016-06-20 14:35:21 -07:00
parent ef178304cb
commit b7ed883aec
1 changed files with 11 additions and 1 deletions

View File

@ -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.