android.net.NetworkRequest Java Examples

The following examples show how to use android.net.NetworkRequest. 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: RequirementsWatcher.java    From TelePlus-Android with GNU General Public License v2.0 7 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #3
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 #4
Source File: JobStore.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Write out a tag with data identifying this job's constraints. If the constraint isn't here
 * it doesn't apply.
 */
private void writeConstraintsToXml(XmlSerializer out, JobStatus jobStatus) throws IOException {
    out.startTag(null, XML_TAG_PARAMS_CONSTRAINTS);
    if (jobStatus.hasConnectivityConstraint()) {
        final NetworkRequest network = jobStatus.getJob().getRequiredNetwork();
        out.attribute(null, "net-capabilities", Long.toString(
                BitUtils.packBits(network.networkCapabilities.getCapabilities())));
        out.attribute(null, "net-unwanted-capabilities", Long.toString(
                BitUtils.packBits(network.networkCapabilities.getUnwantedCapabilities())));

        out.attribute(null, "net-transport-types", Long.toString(
                BitUtils.packBits(network.networkCapabilities.getTransportTypes())));
    }
    if (jobStatus.hasIdleConstraint()) {
        out.attribute(null, "idle", Boolean.toString(true));
    }
    if (jobStatus.hasChargingConstraint()) {
        out.attribute(null, "charging", Boolean.toString(true));
    }
    if (jobStatus.hasBatteryNotLowConstraint()) {
        out.attribute(null, "battery-not-low", Boolean.toString(true));
    }
    out.endTag(null, XML_TAG_PARAMS_CONSTRAINTS);
}
 
Example #5
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 #6
Source File: UpstreamNetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void start(NetworkRequest defaultNetworkRequest) {
    stop();

    final NetworkRequest listenAllRequest = new NetworkRequest.Builder()
            .clearCapabilities().build();
    mListenAllCallback = new UpstreamNetworkCallback(CALLBACK_LISTEN_ALL);
    cm().registerNetworkCallback(listenAllRequest, mListenAllCallback, mHandler);

    if (defaultNetworkRequest != null) {
        // This is not really a "request", just a way of tracking the system default network.
        // It's guaranteed not to actually bring up any networks because it's the same request
        // as the ConnectivityService default request, and thus shares fate with it. We can't
        // use registerDefaultNetworkCallback because it will not track the system default
        // network if there is a VPN that applies to our UID.
        final NetworkRequest trackDefaultRequest = new NetworkRequest(defaultNetworkRequest);
        mDefaultNetworkCallback = new UpstreamNetworkCallback(CALLBACK_DEFAULT_INTERNET);
        cm().requestNetwork(trackDefaultRequest, mDefaultNetworkCallback, mHandler);
    }
}
 
Example #7
Source File: UpstreamNetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public void registerMobileNetworkRequest() {
    if (mMobileNetworkCallback != null) {
        mLog.e("registerMobileNetworkRequest() already registered");
        return;
    }

    // The following use of the legacy type system cannot be removed until
    // after upstream selection no longer finds networks by legacy type.
    // See also http://b/34364553 .
    final int legacyType = mDunRequired ? TYPE_MOBILE_DUN : TYPE_MOBILE_HIPRI;

    final NetworkRequest mobileUpstreamRequest = new NetworkRequest.Builder()
            .setCapabilities(ConnectivityManager.networkCapabilitiesForType(legacyType))
            .build();

    // The existing default network and DUN callbacks will be notified.
    // Therefore, to avoid duplicate notifications, we only register a no-op.
    mMobileNetworkCallback = new UpstreamNetworkCallback(CALLBACK_MOBILE_REQUEST);

    // TODO: Change the timeout from 0 (no onUnavailable callback) to some
    // moderate callback timeout. This might be useful for updating some UI.
    // Additionally, we log a message to aid in any subsequent debugging.
    mLog.i("requesting mobile upstream network: " + mobileUpstreamRequest);

    cm().requestNetwork(mobileUpstreamRequest, mMobileNetworkCallback, 0, legacyType, mHandler);
}
 
Example #8
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
        LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
        NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
    this.messenger = messenger;
    asyncChannel = ac;
    network = net;
    networkInfo = info;
    linkProperties = lp;
    networkCapabilities = nc;
    currentScore = score;
    mConnService = connService;
    mContext = context;
    mHandler = handler;
    networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
    networkMisc = misc;
}
 
Example #9
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private void updateRequestCounts(boolean add, NetworkRequest request) {
    int delta = add ? +1 : -1;
    switch (request.type) {
        case REQUEST:
            mNumRequestNetworkRequests += delta;
            break;

        case BACKGROUND_REQUEST:
            mNumRequestNetworkRequests += delta;
            mNumBackgroundNetworkRequests += delta;
            break;

        case TRACK_DEFAULT:
        case LISTEN:
            break;

        case NONE:
        default:
            Log.wtf(TAG, "Unhandled request type " + request.type);
            break;
    }
}
 
Example #10
Source File: JobSchedulerSchedulerTest.java    From JobSchedulerCompat with MIT License 6 votes vote down vote up
@Test
@Config(sdk = Build.VERSION_CODES.P)
public void testScheduleJobWithPieOption() {
    JobInfo.Builder builder = createJob(1);
    builder.setRequiredNetwork(
            new NetworkRequest.Builder()
                    .addCapability(NET_CAPABILITY_INTERNET)
                    .addCapability(NET_CAPABILITY_VALIDATED)
                    .removeCapability(NET_CAPABILITY_NOT_VPN)
                    .addCapability(NET_CAPABILITY_NOT_ROAMING)
                    .build());
    builder.setEstimatedNetworkBytes(1024, 128);
    builder.setImportantWhileForeground(true);
    builder.setPrefetch(true);
    JobInfo job = builder.build();

    scheduler.schedule(job);

    android.app.job.JobInfo nativeJob = getPendingJob(job.getId());
    assertNotNull(nativeJob);
    assertNativeJobInfoMatchesJobInfo(nativeJob, job);
}
 
Example #11
Source File: SambaProviderApplication.java    From samba-documents-provider with GNU General Public License v3.0 6 votes vote down vote up
private void registerNetworkCallback(Context context) {
  final ConnectivityManager manager =
      (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
  manager.registerNetworkCallback(
      new NetworkRequest.Builder()
          .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
          .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET)
          .build(),
      new NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
          mSambaClient.reset();
        }
      });
}
 
Example #12
Source File: AirplaneModeAndroidTest.java    From firebase-jobdispatcher-android with Apache License 2.0 6 votes vote down vote up
private void waitForSomeNetworkToConnect() throws Exception {
  final SettableFuture<Void> future = SettableFuture.create();

  ConnectivityManager.NetworkCallback cb =
      new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
          NetworkInfo netInfo = connManager.getNetworkInfo(network);
          if (netInfo != null && netInfo.isConnected()) {
            future.set(null);
          }
        }
      };

  connManager.requestNetwork(
      new NetworkRequest.Builder().addCapability(NET_CAPABILITY_INTERNET).build(), cb);

  try {
    future.get(NETWORK_STATE_CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
  } finally {
    connManager.unregisterNetworkCallback(cb);
  }
}
 
Example #13
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 #14
Source File: RequirementsWatcher.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      Assertions.checkNotNull(
          (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #15
Source File: VideoDownloadManager.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
@SuppressWarnings({"MissingPermission"})
private void registerConnectionListener(Context context) {
    NetworkCallbackImpl networkCallback = new NetworkCallbackImpl(mNetworkListener);
    NetworkRequest request = new NetworkRequest.Builder().build();
    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (manager != null) {
        manager.registerNetworkCallback(request, networkCallback);
    }
}
 
Example #16
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 registerNetworkCallback(NetworkCallback networkCallback) {
  connectivityManager.registerNetworkCallback(
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
          .build(),
      networkCallback);
}
 
Example #17
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 #18
Source File: RNWifiModule.java    From react-native-wifi-reborn with ISC License 5 votes vote down vote up
/**
 * Use this to execute api calls to a wifi network that does not have internet access.
 *
 * Useful for commissioning IoT devices.
 *
 * This will route all app network requests to the network (instead of the mobile connection).
 * It is important to disable it again after using as even when the app disconnects from the wifi
 * network it will keep on routing everything to wifi.
 *
 * @param useWifi boolean to force wifi off or on
 */
@ReactMethod
public void forceWifiUsage(final boolean useWifi, final Promise promise) {
    final ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null) {
        promise.reject(ForceWifiUsageErrorCodes.couldNotGetConnectivityManager.toString(), "Failed to get the ConnectivityManager.");
        return;
    }

    if (useWifi) {
        NetworkRequest networkRequest = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .build();
        connectivityManager.requestNetwork(networkRequest, new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(@NonNull final Network network) {
                super.onAvailable(network);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    connectivityManager.bindProcessToNetwork(network);
                } else {
                    ConnectivityManager.setProcessDefaultNetwork(network);
                }

                connectivityManager.unregisterNetworkCallback(this);

                promise.resolve(null);
            }
        });
    } else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            connectivityManager.bindProcessToNetwork(null);
        } else {
            ConnectivityManager.setProcessDefaultNetwork(null);
        }

        promise.resolve(null);
    }
}
 
Example #19
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public ConnectivityController(JobSchedulerService service) {
    super(service);

    mConnManager = mContext.getSystemService(ConnectivityManager.class);
    mNetPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);

    // We're interested in all network changes; internally we match these
    // network changes against the active network for each UID with jobs.
    final NetworkRequest request = new NetworkRequest.Builder().clearCapabilities().build();
    mConnManager.registerNetworkCallback(request, mNetworkCallback);

    mNetPolicyManager.registerListener(mNetPolicyListener);
}
 
Example #20
Source File: ConnectivityController.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@GuardedBy("mLock")
@Override
public void dumpControllerStateLocked(ProtoOutputStream proto, long fieldId,
        Predicate<JobStatus> predicate) {
    final long token = proto.start(fieldId);
    final long mToken = proto.start(StateControllerProto.CONNECTIVITY);

    for (int i = 0; i < mTrackedJobs.size(); i++) {
        final JobStatus js = mTrackedJobs.valueAt(i);
        if (!predicate.test(js)) {
            continue;
        }
        final long jsToken = proto.start(StateControllerProto.ConnectivityController.TRACKED_JOBS);
        js.writeToShortProto(proto, StateControllerProto.ConnectivityController.TrackedJob.INFO);
        proto.write(StateControllerProto.ConnectivityController.TrackedJob.SOURCE_UID,
                js.getSourceUid());
        NetworkRequest rn = js.getJob().getRequiredNetwork();
        if (rn != null) {
            rn.writeToProto(proto,
                    StateControllerProto.ConnectivityController.TrackedJob.REQUIRED_NETWORK);
        }
        proto.end(jsToken);
    }

    proto.end(mToken);
    proto.end(token);
}
 
Example #21
Source File: MultipathPolicyTracker.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void registerTrackMobileCallback() {
    final NetworkRequest request = new NetworkRequest.Builder()
            .addCapability(NET_CAPABILITY_INTERNET)
            .addTransportType(TRANSPORT_CELLULAR)
            .build();
    mMobileNetworkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onCapabilitiesChanged(Network network, NetworkCapabilities nc) {
            MultipathTracker existing = mMultipathTrackers.get(network);
            if (existing != null) {
                existing.setNetworkCapabilities(nc);
                existing.updateMultipathBudget();
                return;
            }

            try {
                mMultipathTrackers.put(network, new MultipathTracker(network, nc));
            } catch (IllegalStateException e) {
                Slog.e(TAG, "Can't track mobile network " + network + ": " + e.getMessage());
            }
            if (DBG) Slog.d(TAG, "Tracking mobile network " + network);
        }

        @Override
        public void onLost(Network network) {
            MultipathTracker existing = mMultipathTrackers.get(network);
            if (existing != null) {
                existing.shutdown();
                mMultipathTrackers.remove(network);
            }
            if (DBG) Slog.d(TAG, "No longer tracking mobile network " + network);
        }
    };

    mCM.registerNetworkCallback(request, mMobileNetworkCallback, mHandler);
}
 
Example #22
Source File: NetworkMonitor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
        NetworkRequest defaultRequest, IpConnectivityLog logger,
        NetworkMonitorSettings settings) {
    // Add suffix indicating which NetworkMonitor we're talking about.
    super(TAG + networkAgentInfo.name());

    // Logs with a tag of the form given just above, e.g.
    //     <timestamp>   862  2402 D NetworkMonitor/NetworkAgentInfo [WIFI () - 100]: ...
    setDbg(VDBG);

    mContext = context;
    mMetricsLog = logger;
    mConnectivityServiceHandler = handler;
    mSettings = settings;
    mNetworkAgentInfo = networkAgentInfo;
    mNetwork = new OneAddressPerFamilyNetwork(networkAgentInfo.network());
    mNetId = mNetwork.netId;
    mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    mDefaultRequest = defaultRequest;

    addState(mDefaultState);
    addState(mMaybeNotifyState, mDefaultState);
        addState(mEvaluatingState, mMaybeNotifyState);
        addState(mCaptivePortalState, mMaybeNotifyState);
    addState(mEvaluatingPrivateDnsState, mDefaultState);
    addState(mValidatedState, mDefaultState);
    setInitialState(mDefaultState);

    mIsCaptivePortalCheckEnabled = getIsCaptivePortalCheckEnabled();
    mUseHttps = getUseHttpsValidation();
    mCaptivePortalUserAgent = getCaptivePortalUserAgent();
    mCaptivePortalHttpsUrl = makeURL(getCaptivePortalServerHttpsUrl());
    mCaptivePortalHttpUrl = makeURL(getCaptivePortalServerHttpUrl(settings, context));
    mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls();
    mCaptivePortalFallbackSpecs = makeCaptivePortalFallbackProbeSpecs();

    start();
}
 
Example #23
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Add {@code networkRequest} to this network as it's satisfied by this network.
 * @return true if {@code networkRequest} was added or false if {@code networkRequest} was
 *         already present.
 */
public boolean addRequest(NetworkRequest networkRequest) {
    NetworkRequest existing = mNetworkRequests.get(networkRequest.requestId);
    if (existing == networkRequest) return false;
    if (existing != null) {
        // Should only happen if the requestId wraps. If that happens lots of other things will
        // be broken as well.
        Log.wtf(TAG, String.format("Duplicate requestId for %s and %s on %s",
                networkRequest, existing, name()));
        updateRequestCounts(REMOVE, existing);
    }
    mNetworkRequests.put(networkRequest.requestId, networkRequest);
    updateRequestCounts(ADD, networkRequest);
    return true;
}
 
Example #24
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Remove the specified request from this network.
 */
public void removeRequest(int requestId) {
    NetworkRequest existing = mNetworkRequests.get(requestId);
    if (existing == null) return;
    updateRequestCounts(REMOVE, existing);
    mNetworkRequests.remove(requestId);
    if (existing.isRequest()) {
        unlingerRequest(existing);
    }
}
 
Example #25
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the specified request to linger on this network for the specified time. Called by
 * ConnectivityService when the request is moved to another network with a higher score.
 */
public void lingerRequest(NetworkRequest request, long now, long duration) {
    if (mLingerTimerForRequest.get(request.requestId) != null) {
        // Cannot happen. Once a request is lingering on a particular network, we cannot
        // re-linger it unless that network becomes the best for that request again, in which
        // case we should have unlingered it.
        Log.wtf(TAG, this.name() + ": request " + request.requestId + " already lingered");
    }
    final long expiryMs = now + duration;
    LingerTimer timer = new LingerTimer(request, expiryMs);
    if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + this.name());
    mLingerTimers.add(timer);
    mLingerTimerForRequest.put(request.requestId, timer);
}
 
Example #26
Source File: NetworkAgentInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Cancel lingering. Called by ConnectivityService when a request is added to this network.
 * Returns true if the given request was lingering on this network, false otherwise.
 */
public boolean unlingerRequest(NetworkRequest request) {
    LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
    if (timer != null) {
        if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + this.name());
        mLingerTimers.remove(timer);
        mLingerTimerForRequest.remove(request.requestId);
        return true;
    }
    return false;
}
 
Example #27
Source File: JobInfo.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private JobInfo(Parcel in) {
    jobId = in.readInt();
    extras = in.readPersistableBundle();
    transientExtras = in.readBundle();
    if (in.readInt() != 0) {
        clipData = ClipData.CREATOR.createFromParcel(in);
        clipGrantFlags = in.readInt();
    } else {
        clipData = null;
        clipGrantFlags = 0;
    }
    service = in.readParcelable(null);
    constraintFlags = in.readInt();
    triggerContentUris = in.createTypedArray(TriggerContentUri.CREATOR);
    triggerContentUpdateDelay = in.readLong();
    triggerContentMaxDelay = in.readLong();
    if (in.readInt() != 0) {
        networkRequest = NetworkRequest.CREATOR.createFromParcel(in);
    } else {
        networkRequest = null;
    }
    networkDownloadBytes = in.readLong();
    networkUploadBytes = in.readLong();
    minLatencyMillis = in.readLong();
    maxExecutionDelayMillis = in.readLong();
    isPeriodic = in.readInt() == 1;
    isPersisted = in.readInt() == 1;
    intervalMillis = in.readLong();
    flexMillis = in.readLong();
    initialBackoffMillis = in.readLong();
    backoffPolicy = in.readInt();
    hasEarlyConstraint = in.readInt() == 1;
    hasLateConstraint = in.readInt() == 1;
    priority = in.readInt();
    flags = in.readInt();
}
 
Example #28
Source File: RequirementsWatcher.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
@TargetApi(23)
private void registerNetworkCallbackV23() {
  ConnectivityManager connectivityManager =
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkRequest request =
      new NetworkRequest.Builder()
          .addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
          .build();
  networkCallback = new CapabilityValidatedCallback();
  connectivityManager.registerNetworkCallback(request, networkCallback);
}
 
Example #29
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 #30
Source File: ConnectorUtils.java    From WifiUtils with Apache License 2.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.Q)
private static boolean connectAndroidQ(@Nullable ConnectivityManager connectivityManager, @NonNull ScanResult scanResult, @NonNull String password) {
    if (connectivityManager == null) {
        return false;
    }

    WifiNetworkSpecifier.Builder wifiNetworkSpecifierBuilder = new WifiNetworkSpecifier.Builder()
            .setSsid(scanResult.SSID)
            .setBssid(MacAddress.fromString(scanResult.BSSID));

    final String security = ConfigSecurities.getSecurity(scanResult);

    ConfigSecurities.setupWifiNetworkSpecifierSecurities(wifiNetworkSpecifierBuilder, security, password);


    NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
            .setNetworkSpecifier(wifiNetworkSpecifierBuilder.build())
            .build();

    // not sure, if this is needed
    if (networkCallback != null) {
        connectivityManager.unregisterNetworkCallback(networkCallback);
    }

    networkCallback = new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(@NonNull Network network) {
            super.onAvailable(network);

            wifiLog("AndroidQ+ connected to wifi ");

            // bind so all api calls are performed over this new network
            connectivityManager.bindProcessToNetwork(network);
        }

        @Override
        public void onUnavailable() {
            super.onUnavailable();

            wifiLog("AndroidQ+ could not connect to wifi");
        }
    };

    connectivityManager.requestNetwork(networkRequest, networkCallback);

    return true;
}