Skip to content

Commit 5ded152

Browse files
committed
Catch and log warning if ACCESS_NETWORK_STATE permission is not granted
1 parent 289c8c4 commit 5ded152

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

android/src/main/java/io/grpc/android/AndroidChannelBuilder.java

+16-2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import android.net.Network;
2626
import android.net.NetworkInfo;
2727
import android.os.Build;
28+
import android.util.Log;
2829
import com.google.common.annotations.VisibleForTesting;
2930
import io.grpc.CallOptions;
3031
import io.grpc.ClientCall;
@@ -50,6 +51,8 @@
5051
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/4056")
5152
public final class AndroidChannelBuilder extends ForwardingChannelBuilder<AndroidChannelBuilder> {
5253

54+
private static final String LOG_TAG = "AndroidChannelBuilder";
55+
5356
@Nullable private static final Class<?> OKHTTP_CHANNEL_BUILDER_CLASS = findOkHttp();
5457

5558
private static final Class<?> findOkHttp() {
@@ -136,11 +139,22 @@ static final class AndroidChannel extends ManagedChannel {
136139

137140
@GuardedBy("lock")
138141
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+
139155
// Android N added the registerDefaultNetworkCallback API to listen to changes in the device's
140156
// default network. For earlier Android API levels, use the BroadcastReceiver API.
141157
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && connectivityManager != null) {
142-
NetworkInfo currentNetwork = connectivityManager.getActiveNetworkInfo();
143-
144158
// The connection status may change before registration of the listener is complete, but
145159
// this will at worst result in invoking resetConnectBackoff() instead of enterIdle() (or
146160
// vice versa) on the first network change.

0 commit comments

Comments
 (0)