|
| 1 | +/* |
| 2 | + * Copyright 2026 The Android Open Source Project |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package com.example.wear.snippets.network |
| 18 | + |
| 19 | +import android.content.Context |
| 20 | +import android.content.Intent |
| 21 | +import android.net.ConnectivityManager |
| 22 | +import android.net.Network |
| 23 | +import android.net.NetworkCapabilities |
| 24 | +import android.net.NetworkRequest |
| 25 | + |
| 26 | +class NetworkSnippets(val connectivityManager: ConnectivityManager) { |
| 27 | + |
| 28 | + // [START android_wear_request_network] |
| 29 | + val callback = object : ConnectivityManager.NetworkCallback() { |
| 30 | + override fun onAvailable(network: Network) { |
| 31 | + super.onAvailable(network) |
| 32 | + // The Wi-Fi network has been acquired. Bind it to use this network by default. |
| 33 | + connectivityManager.bindProcessToNetwork(network) |
| 34 | + } |
| 35 | + |
| 36 | + override fun onLost(network: Network) { |
| 37 | + super.onLost(network) |
| 38 | + // Called when a network disconnects or otherwise no longer satisfies this request |
| 39 | + // or callback. |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + fun requestWifiNetwork() { |
| 44 | + connectivityManager.requestNetwork( |
| 45 | + NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build(), |
| 46 | + callback |
| 47 | + ) |
| 48 | + } |
| 49 | + // [END android_wear_request_network] |
| 50 | + |
| 51 | + fun unregisterNetwork() { |
| 52 | + // [START android_wear_unregister_network] |
| 53 | + connectivityManager.bindProcessToNetwork(null) |
| 54 | + connectivityManager.unregisterNetworkCallback(callback) |
| 55 | + // [END android_wear_unregister_network] |
| 56 | + } |
| 57 | + |
| 58 | + fun launchSettings(context: Context) { |
| 59 | + // [START android_wear_launch_settings] |
| 60 | + val networkSettingsAction = "com.google.android.clockwork.settings.connectivity.wifi.ADD_NETWORK_SETTINGS" |
| 61 | + val intent = Intent(networkSettingsAction).apply { |
| 62 | + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) |
| 63 | + } |
| 64 | + context.startActivity(intent) |
| 65 | + // [END android_wear_launch_settings] |
| 66 | + } |
| 67 | +} |
0 commit comments