Java Code Examples for android.net.NetworkRequest#Builder

The following examples show how to use android.net.NetworkRequest#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TcpSocketModule.java    From react-native-tcp-socket with MIT License 7 votes vote down vote up
private void requestNetwork(final int transportType) throws InterruptedException {
    final NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
    requestBuilder.addTransportType(transportType);
    final CountDownLatch awaitingNetwork = new CountDownLatch(1); // only needs to be counted down once to release waiting threads
    final ConnectivityManager cm = (ConnectivityManager) mReactContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.requestNetwork(requestBuilder.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            currentNetwork.setNetwork(network);
            awaitingNetwork.countDown(); // Stop waiting
        }

        @Override
        public void onUnavailable() {
            awaitingNetwork.countDown(); // Stop waiting
        }
    });
    // Timeout if there the network is unreachable
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    exec.schedule(new Runnable() {
        public void run() {
            awaitingNetwork.countDown(); // Stop waiting
        }
    }, 5, TimeUnit.SECONDS);
    awaitingNetwork.await();
}
 
Example 2
Source File: FragmentOptionsConnection.java    From FairEmail with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onResume() {
    super.onResume();

    ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (cm == null)
        return;

    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    cm.registerNetworkCallback(builder.build(), networkCallback);
}
 
Example 3
Source File: GnssLocationProvider.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void handleRequestSuplConnection(InetAddress address) {
    if (DEBUG) {
        String message = String.format(
                "requestSuplConnection, state=%s, address=%s",
                agpsDataConnStateAsString(),
                address);
        Log.d(TAG, message);
    }

    if (mAGpsDataConnectionState != AGPS_DATA_CONNECTION_CLOSED) {
        return;
    }
    mAGpsDataConnectionIpAddr = address;
    mAGpsDataConnectionState = AGPS_DATA_CONNECTION_OPENING;

    NetworkRequest.Builder requestBuilder = new NetworkRequest.Builder();
    requestBuilder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
    requestBuilder.addCapability(NetworkCapabilities.NET_CAPABILITY_SUPL);
    NetworkRequest request = requestBuilder.build();
    mConnMgr.requestNetwork(
            request,
            mSuplConnectivityCallback);
}
 
Example 4
Source File: PhoneUtils.java    From Mobilyzer with Apache License 2.0 6 votes vote down vote up
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{
			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);

	}
 
Example 5
Source File: NetworkMonitorAutoDetect.java    From webrtc_android with MIT License 5 votes vote down vote up
/** Only callable on Lollipop and newer releases. */
@SuppressLint("NewApi")
public void requestMobileNetwork(NetworkCallback networkCallback) {
  NetworkRequest.Builder builder = new NetworkRequest.Builder();
  builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
      .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
  connectivityManager.requestNetwork(builder.build(), networkCallback);
}
 
Example 6
Source File: ESPDevice.java    From esp-idf-provisioning-android with Apache License 2.0 5 votes vote down vote up
@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
private void enableOnlyWifiNetwork() {

    Log.d(TAG, "enableOnlyWifiNetwork()");

    NetworkRequest.Builder request = new NetworkRequest.Builder();
    request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);

    networkCallback = new ConnectivityManager.NetworkCallback() {

        @Override
        public void onAvailable(Network network) {

            Log.e(TAG, "Network is available - 3");
            connectivityManager.bindProcessToNetwork(network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();
            Log.e(TAG, "Network is Unavailable - 3");
        }

        @Override
        public void onLost(@NonNull Network network) {
            super.onLost(network);
            Log.e(TAG, "Lost Network Connection - 3");
        }
    };
    connectivityManager.registerNetworkCallback(request.build(), networkCallback);
}
 
Example 7
Source File: JobInfo.java    From JobSchedulerCompat with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.P)
private void syncRequiredNetworkAndType(NetworkRequest networkRequest, Integer networkType) {
    if (networkType == null) {
        if (networkRequest == null) {
            this.networkType = NETWORK_TYPE_NONE;
        } else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
            this.networkType = NETWORK_TYPE_UNMETERED;
        } else if (networkRequest.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING)) {
            this.networkType = NETWORK_TYPE_NOT_ROAMING;
        } else if (networkRequest.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            this.networkType = NETWORK_TYPE_CELLULAR;
        } else {
            this.networkType = NETWORK_TYPE_ANY;
        }
    } else {
        final NetworkRequest.Builder builder = new NetworkRequest.Builder();
        builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        builder.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
        builder.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN);
        if (networkType == NETWORK_TYPE_UNMETERED) {
            builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
        } else if (networkType == NETWORK_TYPE_NOT_ROAMING) {
            builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
        } else if (networkType == NETWORK_TYPE_CELLULAR) {
            builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
        }
        this.networkRequest = builder.build();
    }
}
 
Example 8
Source File: AndroidDnsServer.java    From happy-dns-android with MIT License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
AndroidResolver(Context context){
    networkCallback = false;

    List<InetAddress> addresses = getByReflection();
    if (addresses == null) {
        addresses = getByCommand();
    }

    if(addresses == null){
        ///Android 8 , net.dns* was disabled, query dns servers must use network callback
        ///@see https://developer.android.com/about/versions/oreo/android-8.0-changes.html
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager connectivityManager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkRequest.Builder builder = new NetworkRequest.Builder();

            connectivityManager.registerNetworkCallback(builder.build(),
                    new ConnectivityManager.NetworkCallback(){

                        @Override
                        public void onLinkPropertiesChanged(Network network, LinkProperties linkProperties) {

                            if(linkProperties != null)
                                dnsServers.addAll(linkProperties.getDnsServers());

                            networkCallback = true;
                        }

                    });
        }
    }
    else {
        dnsServers.addAll(addresses);
    }


}
 
Example 9
Source File: JobInfo.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Set basic description of the kind of network your job requires. If
 * you need more precise control over network capabilities, see
 * {@link #setRequiredNetwork(NetworkRequest)}.
 * <p>
 * If your job doesn't need a network connection, you don't need to call
 * this method, as the default value is {@link #NETWORK_TYPE_NONE}.
 * <p>
 * Calling this method defines network as a strict requirement for your
 * job. If the network requested is not available your job will never
 * run. See {@link #setOverrideDeadline(long)} to change this behavior.
 * Calling this method will override any requirements previously defined
 * by {@link #setRequiredNetwork(NetworkRequest)}; you typically only
 * want to call one of these methods.
 * <p class="note">
 * When your job executes in
 * {@link JobService#onStartJob(JobParameters)}, be sure to use the
 * specific network returned by {@link JobParameters#getNetwork()},
 * otherwise you'll use the default network which may not meet this
 * constraint.
 *
 * @see #setRequiredNetwork(NetworkRequest)
 * @see JobInfo#getNetworkType()
 * @see JobParameters#getNetwork()
 */
public Builder setRequiredNetworkType(@NetworkType int networkType) {
    if (networkType == NETWORK_TYPE_NONE) {
        return setRequiredNetwork(null);
    } else {
        final NetworkRequest.Builder builder = new NetworkRequest.Builder();

        // All types require validated Internet
        builder.addCapability(NET_CAPABILITY_INTERNET);
        builder.addCapability(NET_CAPABILITY_VALIDATED);
        builder.removeCapability(NET_CAPABILITY_NOT_VPN);

        if (networkType == NETWORK_TYPE_ANY) {
            // No other capabilities
        } else if (networkType == NETWORK_TYPE_UNMETERED) {
            builder.addCapability(NET_CAPABILITY_NOT_METERED);
        } else if (networkType == NETWORK_TYPE_NOT_ROAMING) {
            builder.addCapability(NET_CAPABILITY_NOT_ROAMING);
        } else if (networkType == NETWORK_TYPE_CELLULAR) {
            builder.addTransportType(TRANSPORT_CELLULAR);
        }

        return setRequiredNetwork(builder.build());
    }
}
 
Example 10
Source File: ServiceSend.java    From FairEmail with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onCreate() {
    EntityLog.log(this, "Service send create");
    super.onCreate();
    startForeground(Helper.NOTIFICATION_SEND, getNotificationService().build());

    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wlOutbox = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, BuildConfig.APPLICATION_ID + ":send");

    // Observe unsent count
    DB db = DB.getInstance(this);
    db.operation().liveUnsent().observe(this, new Observer<TupleUnsent>() {
        @Override
        public void onChanged(TupleUnsent unsent) {
            if (unsent == null || !unsent.equals(lastUnsent)) {
                lastUnsent = unsent;

                try {
                    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    nm.notify(Helper.NOTIFICATION_SEND, getNotificationService().build());
                } catch (Throwable ex) {
                    Log.w(ex);
                }
            }
        }
    });

    // Observe send operations
    db.operation().liveOperations(null).observe(owner, new Observer<List<TupleOperationEx>>() {
        @Override
        public void onChanged(List<TupleOperationEx> operations) {
            if (operations == null)
                operations = new ArrayList<>();

            if (operations.size() == 0)
                stopSelf();

            final List<TupleOperationEx> process = new ArrayList<>();

            List<Long> ops = new ArrayList<>();
            for (TupleOperationEx op : operations) {
                if (!handling.contains(op.id))
                    process.add(op);
                ops.add(op.id);
            }
            handling = ops;

            if (process.size() > 0) {
                Log.i("OUTBOX process=" + TextUtils.join(",", process) +
                        " handling=" + TextUtils.join(",", handling));

                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        processOperations(process);
                    }
                });
            }
        }
    });

    lastSuitable = ConnectionHelper.getNetworkState(this).isSuitable();
    if (lastSuitable)
        owner.start();

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
    cm.registerNetworkCallback(builder.build(), networkCallback);

    IntentFilter iif = new IntentFilter();
    iif.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    iif.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    registerReceiver(connectionChangedReceiver, iif);
}