|
25 | 25 | import android.net.Network;
|
26 | 26 | import android.net.NetworkInfo;
|
27 | 27 | import android.os.Build;
|
| 28 | +import android.util.Log; |
28 | 29 | import com.google.common.annotations.VisibleForTesting;
|
29 | 30 | import io.grpc.CallOptions;
|
30 | 31 | import io.grpc.ClientCall;
|
|
50 | 51 | @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4056")
|
51 | 52 | public final class AndroidChannelBuilder extends ForwardingChannelBuilder<AndroidChannelBuilder> {
|
52 | 53 |
|
| 54 | + private static final String LOG_TAG = "AndroidChannelBuilder"; |
| 55 | + |
53 | 56 | @Nullable private static final Class<?> OKHTTP_CHANNEL_BUILDER_CLASS = findOkHttp();
|
54 | 57 |
|
55 | 58 | private static final Class<?> findOkHttp() {
|
@@ -136,11 +139,22 @@ static final class AndroidChannel extends ManagedChannel {
|
136 | 139 |
|
137 | 140 | @GuardedBy("lock")
|
138 | 141 | private void configureNetworkMonitoring() {
|
| 142 | + // Eagerly check current network state to verify app has required permissions |
| 143 | + NetworkInfo currentNetwork; |
| 144 | + try { |
| 145 | + currentNetwork = connectivityManager.getActiveNetworkInfo(); |
| 146 | + } catch (SecurityException e) { |
| 147 | + Log.w( |
| 148 | + LOG_TAG, |
| 149 | + "Failed to configure network monitoring. Does app have ACCESS_NETWORK_STATE" |
| 150 | + + " permission?", |
| 151 | + e); |
| 152 | + return; |
| 153 | + } |
| 154 | + |
139 | 155 | // Android N added the registerDefaultNetworkCallback API to listen to changes in the device's
|
140 | 156 | // default network. For earlier Android API levels, use the BroadcastReceiver API.
|
141 | 157 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && connectivityManager != null) {
|
142 |
| - NetworkInfo currentNetwork = connectivityManager.getActiveNetworkInfo(); |
143 |
| - |
144 | 158 | // The connection status may change before registration of the listener is complete, but
|
145 | 159 | // this will at worst result in invoking resetConnectBackoff() instead of enterIdle() (or
|
146 | 160 | // vice versa) on the first network change.
|
|
0 commit comments