Example usage for android.net ConnectivityManager requestNetwork

List of usage examples for android.net ConnectivityManager requestNetwork

Introduction

In this page you can find the example usage for android.net ConnectivityManager requestNetwork.

Prototype

public void requestNetwork(@NonNull NetworkRequest request, @NonNull PendingIntent operation) 

Source Link

Document

Request a network to satisfy a set of android.net.NetworkCapabilities .

Usage

From source file:org.universAAL.android.services.MiddlewareService.java

/**
 * Helper method to determine if there is a WiFi data connection.
 * /*from w  ww . j av  a2s.  c om*/
 * @return True if there is one.
 */
//   private boolean isWifiOn(){
//      try {
//         Thread.sleep(3000);
//      } catch (InterruptedException e) {
//         e.printStackTrace();
//      }
//      ConnectivityManager connectivityManager = (ConnectivityManager) MiddlewareService.this
//            .getSystemService(Context.CONNECTIVITY_SERVICE);
//      NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
//      return (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI);
//   }

@SuppressLint("NewApi")
private void requestLollipopWifi() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ConnectivityManager connectivityManager = (ConnectivityManager) MiddlewareService.this
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        connectivityManager.requestNetwork(
                new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build(),
                new ConnectivityManager.NetworkCallback() {
                    public void onAvailable(Network network) {
                        Log.d(TAG, "Setting process default network " + network.toString());
                        ConnectivityManager.setProcessDefaultNetwork(network);
                    }
                });
    }
}

From source file:com.mobilyzer.util.PhoneUtils.java

public void switchNetwork(boolean toWiFi, CountDownLatch latch) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder request = new NetworkRequest.Builder();

    if (toWiFi) {
        request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
    } else {/*from   w ww  .  jav a 2s. com*/
        request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    }
    request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    ////      request.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
    //      ConnectivityManager.NetworkCallback connectivityNetworkCallback = new ConnectivityNetworkCallback(latch, cm);
    connectivityNetworkCallback = new ConnectivityNetworkCallback(latch, cm);
    cm.requestNetwork(request.build(), connectivityNetworkCallback);

}