1# AndroidChannelBuilder 2 3 The `grpc-android` package provides access to the 4`AndroidChannelBuilder` class. Given an Android Context, this builder 5registers a network event listener upon channel construction. The listener 6automatically responds to changes in the device's network state, avoiding 7delays and interrupted RPCs that may otherwise occur. 8 9By default, gRPC uses exponential backoff to recover from connection failures. 10Depending on the scheduled backoff delay when the device regains connectivity, 11this could result in a one minute or longer delay before gRPC re-establishes 12the connection. This delay is removed when `AndroidChannelBuilder` is provided 13with the app's Android Context. Notifications from the network listener 14cause the channel to immediately reconnect upon network recovery. 15 16On Android API levels 24+, `AndroidChannelBuilder`'s network listener mechanism 17allows graceful switching from cellular to wifi connections. When an Android 18device on a cellular network connects to a wifi network, there is a brief 19(typically 30 second) interval when both cellular and wifi networks remain 20available, then any connections on the cellular network are terminated. By 21listening for changes in the device's default network, `AndroidChannelBuilder` 22sends new RPCs via wifi rather than using an already-established cellular 23connection. Without listening for pending network changes, new RPCs sent on an 24already established cellular connection would fail when the device terminates 25cellular connections. 26 27***Note:*** *Currently, `AndroidChannelBuilder` is only compatible with gRPC 28OkHttp. We plan to offer additional Android-specific features compatible with 29both the OkHttp and Cronet transports in the future, but the network listener 30mechanism is only necessary with OkHttp; the Cronet library internally handles 31connection management on Android devices.* 32 33## Example usage: 34 35In your `build.gradle` file, include a dependency on both `io.grpc:grpc-android` and 36`io.grpc:grpc-okhttp`. 37 38You also need permission to access the device's network state in your 39`AndroidManifest.xml`: 40 41``` 42<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 43``` 44 45When constructing your channel, use `AndroidChannelBuilder` and provide it with 46your app's Context: 47 48``` 49import io.grpc.android.AndroidChannelBuilder; 50... 51ManagedChannel channel = AndroidChannelBuilder.forAddress("localhost", 8080) 52 .context(getApplicationContext()) 53 .build(); 54``` 55 56You continue to use the constructed channel exactly as you would any other 57channel. gRPC will now monitor and respond to the device's network state 58automatically. When you shutdown the managed channel, the network listener 59registered by `AndroidChannelBuilder` will be unregistered. 60 61