1 /* 2 * Copyright (C) 2019 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 * http://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 android.ext.services.watchdog; 18 19 import android.net.ConnectivityManager; 20 import android.net.Network; 21 import android.net.NetworkCapabilities; 22 import android.net.NetworkRequest; 23 import android.service.watchdog.ExplicitHealthCheckService; 24 25 import androidx.annotation.GuardedBy; 26 27 /** 28 * Observes the network stack via the ConnectivityManager. 29 */ 30 final class NetworkChecker extends ConnectivityManager.NetworkCallback 31 implements ExplicitHealthChecker { 32 private static final String TAG = "NetworkChecker"; 33 34 private final Object mLock = new Object(); 35 private final ExplicitHealthCheckService mService; 36 private final String mPackageName; 37 @GuardedBy("mLock") 38 private boolean mIsPending; 39 NetworkChecker(ExplicitHealthCheckService service, String packageName)40 NetworkChecker(ExplicitHealthCheckService service, String packageName) { 41 mService = service; 42 mPackageName = packageName; 43 } 44 45 @Override request()46 public void request() { 47 synchronized (mLock) { 48 if (mIsPending) { 49 return; 50 } 51 mService.getSystemService(ConnectivityManager.class).registerNetworkCallback( 52 new NetworkRequest.Builder().build(), this); 53 mIsPending = true; 54 } 55 } 56 57 @Override cancel()58 public void cancel() { 59 synchronized (mLock) { 60 if (!mIsPending) { 61 return; 62 } 63 mService.getSystemService(ConnectivityManager.class).unregisterNetworkCallback(this); 64 mIsPending = false; 65 } 66 } 67 68 @Override isPending()69 public boolean isPending() { 70 synchronized (mLock) { 71 return mIsPending; 72 } 73 } 74 75 @Override getSupportedPackageName()76 public String getSupportedPackageName() { 77 return mPackageName; 78 } 79 80 // TODO(b/120598832): Also monitor NetworkCallback#onAvailable to see if we have any 81 // available networks that may be unusable. This could be additional signal to our heuristics 82 @Override onCapabilitiesChanged(Network network, NetworkCapabilities capabilities)83 public void onCapabilitiesChanged(Network network, NetworkCapabilities capabilities) { 84 synchronized (mLock) { 85 if (mIsPending 86 && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 87 mService.notifyHealthCheckPassed(mPackageName); 88 cancel(); 89 } 90 } 91 } 92 } 93