Before 2022/Android

NetworkCallback을 이용하여 네트워크 상태를 받아오자.

Eljoe 2019. 7. 11. 11:05
@Override
protected void onCreate(Bundle savedInstanceState) {
  ....
  ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext()
  	.getSystemService(Context.CONNECTIVITY_SERVICE);

  // Builder 선언
  NetworkRequest.Builder wifiBuilder = new NetworkRequest.Builder();

  // 콜백이 호출되는 조건
  // TRANSPORT_WIFI = WIFI 상태 / TRANSPORT_CELLULAR = Mobile 네트워크 상태
  wifiBuilder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

  // 해당 콜백 등록
  connectivityManager.registerNetworkCallback(wifiBuilder.build(), wifiCallback);
}

// Inner Class
private ConnectivityManager.NetworkCallback wifiCallback = new ConnectivityManager.NetworkCallback() {
  @Override
  public void onAvailable(Network network) {
    super.onAvailable(network);
    Log.e("onAvailable", "WI-FI 연결됨");
  }

  @Override
  public void onLost(Network network) {
    super.onLost(network);
    Log.e("onAvailable", "WI-FI 연결 끊김");
  }
};

@Override
protected void onDestroy() {
  // 콜백 해제
  connectivityManager.unregisterNetworkCallback(wifiCallback);
}