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: 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 #2
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 #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: 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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Constructs a NetworkChangeNotifierAutoDetect.  Lives on calling thread, receives broadcast
 * notifications on the UI thread and forwards the notifications to be processed on the calling
 * thread.
 * @param policy The RegistrationPolicy which determines when this class should watch
 *     for network changes (e.g. see (@link RegistrationPolicyAlwaysRegister} and
 *     {@link RegistrationPolicyApplicationStatus}).
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NetworkChangeNotifierAutoDetect(Observer observer, RegistrationPolicy policy) {
    mLooper = Looper.myLooper();
    mHandler = new Handler(mLooper);
    mObserver = observer;
    mConnectivityManagerDelegate =
            new ConnectivityManagerDelegate(ContextUtils.getApplicationContext());
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        mWifiManagerDelegate = new WifiManagerDelegate(ContextUtils.getApplicationContext());
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNetworkCallback = new MyNetworkCallback();
        mNetworkRequest = new NetworkRequest.Builder()
                                  .addCapability(NET_CAPABILITY_INTERNET)
                                  // Need to hear about VPNs too.
                                  .removeCapability(NET_CAPABILITY_NOT_VPN)
                                  .build();
    } else {
        mNetworkCallback = null;
        mNetworkRequest = null;
    }
    mDefaultNetworkCallback = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
            ? new DefaultNetworkCallback()
            : null;
    mNetworkState = getCurrentNetworkState();
    mIntentFilter = new NetworkConnectivityIntentFilter();
    mIgnoreNextBroadcast = false;
    mShouldSignalObserver = false;
    mRegistrationPolicy = policy;
    mRegistrationPolicy.init(this);
    mShouldSignalObserver = true;
}
 
Example #15
Source File: WifiUtil.java    From android-wificonnect with MIT License 5 votes vote down vote up
@TargetApi(LOLLIPOP)
void bindToNetwork(final String networkSSID, final NetworkStateChangeListener listener) {
    if (SDK_INT < LOLLIPOP) {
        logger.i("SDK version is below Lollipop. No need to bind process to network. Skipping...");
        return;
    }
    logger.i("Currently active network is not " + networkSSID + ", would bind the app to use this when available");

    NetworkRequest request = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build();
    networkCallback = networkCallback(networkSSID, listener);
    manager.registerNetworkCallback(request, networkCallback);
}
 
Example #16
Source File: ConnectivityNetworkCallback.java    From unity-ads-android with Apache License 2.0 5 votes vote down vote up
public static void register() {
	if(_impl == null) {
		_impl = new ConnectivityNetworkCallback();

		ConnectivityManager cm = (ConnectivityManager) ClientProperties.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
		cm.registerNetworkCallback(new NetworkRequest.Builder().build(), _impl);
	}
}
 
Example #17
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 #18
Source File: NetworkChangeNotifierAutoDetect.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a NetworkChangeNotifierAutoDetect.  Lives on calling thread, receives broadcast
 * notifications on the UI thread and forwards the notifications to be processed on the calling
 * thread.
 * @param policy The RegistrationPolicy which determines when this class should watch
 *     for network changes (e.g. see (@link RegistrationPolicyAlwaysRegister} and
 *     {@link RegistrationPolicyApplicationStatus}).
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public NetworkChangeNotifierAutoDetect(Observer observer, RegistrationPolicy policy) {
    mLooper = Looper.myLooper();
    mHandler = new Handler(mLooper);
    mObserver = observer;
    mConnectivityManagerDelegate =
            new ConnectivityManagerDelegate(ContextUtils.getApplicationContext());
    mWifiManagerDelegate = new WifiManagerDelegate(ContextUtils.getApplicationContext());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNetworkCallback = new MyNetworkCallback();
        mNetworkRequest = new NetworkRequest.Builder()
                                  .addCapability(NET_CAPABILITY_INTERNET)
                                  // Need to hear about VPNs too.
                                  .removeCapability(NET_CAPABILITY_NOT_VPN)
                                  .build();
    } else {
        mNetworkCallback = null;
        mNetworkRequest = null;
    }
    mNetworkState = getCurrentNetworkState();
    mIntentFilter = new NetworkConnectivityIntentFilter();
    mIgnoreNextBroadcast = false;
    mShouldSignalObserver = false;
    mRegistrationPolicy = policy;
    mRegistrationPolicy.init(this);
    mShouldSignalObserver = true;
}
 
Example #19
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 #20
Source File: ConnectivityHelper.java    From libcommon with Apache License 2.0 5 votes vote down vote up
@SuppressLint("NewApi")
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
private void init() {
	if (DEBUG) Log.v(TAG, "init:");
	final ConnectivityManager manager = requireConnectivityManager();
	if (BuildCheck.isAPI21()) {
		mOnNetworkActiveListener = new MyOnNetworkActiveListener();
		manager.addDefaultNetworkActiveListener(mOnNetworkActiveListener);	// API>=21
		mNetworkCallback = new MyNetworkCallback();
		// ACCESS_NETWORK_STATEパーミッションが必要
		if (BuildCheck.isAPI23()) {
			updateActiveNetwork(manager.getActiveNetwork());	// API>=23
			if (BuildCheck.isAPI24()) {
				manager.registerDefaultNetworkCallback(mNetworkCallback);	// API>=24
			} else if (BuildCheck.isAPI26()) {
				manager.registerDefaultNetworkCallback(mNetworkCallback, mAsyncHandler); // API>=26
			}
		} else {
			manager.registerNetworkCallback(
				new NetworkRequest.Builder().build(),
				mNetworkCallback);	// API>=21
		}
	} else {
		mNetworkChangedReceiver = new NetworkChangedReceiver(this);
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION_GLOBAL_CONNECTIVITY_CHANGE);
		requireContext().registerReceiver(mNetworkChangedReceiver, intentFilter);
	}
}
 
Example #21
Source File: TransmitterActivity.java    From sample-lowpan with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the network.
 */
private void resetNetwork() {
    // Initialize network
    onNoNetwork();
    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest networkRequest = new NetworkRequest.Builder()
            .addTransportType(NetworkCapabilities.TRANSPORT_LOWPAN)
            .build();
    mBackgroundHandlerThread = new HandlerThread(TAG);
    mBackgroundHandlerThread.start();
    mHandler = new Handler(mBackgroundHandlerThread.getLooper());
    // Make sure that it is connected to a valid network
    mConnectivityManager.registerNetworkCallback(networkRequest,
            mNetworkCallback, mUiThreadHandler);
}
 
Example #22
Source File: RequirementsWatcher.java    From Telegram-FOSS with GNU General Public License v2.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 #23
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 #24
Source File: JobInfo.java    From JobSchedulerCompat with MIT License 5 votes vote down vote up
/** @see android.app.job.JobInfo.Builder#setRequiredNetwork(NetworkRequest) */
@RequiresApi(Build.VERSION_CODES.P)
public Builder setRequiredNetwork(NetworkRequest networkRequest) {
    this.networkRequest = networkRequest;
    syncRequiredNetworkAndType(networkRequest, null);
    return this;
}
 
Example #25
Source File: JobInfo.java    From JobSchedulerCompat with MIT License 5 votes vote down vote up
@RestrictTo(RestrictTo.Scope.LIBRARY)
public JobInfo(int jobId, ComponentName service, PersistableBundle extras, Bundle transientExtras,
               ClipData clipData, int clipGrantFlags, int constraintFlags, TriggerContentUri[] triggerContentUris,
               long triggerContentUpdateDelay, long triggerContentMaxDelay, boolean hasEarlyConstraint,
               boolean hasLateConstraint, int networkType, NetworkRequest networkRequest, long networkDownloadBytes,
               long networkUploadBytes, long minLatencyMillis, long maxExecutionDelayMillis, boolean isPeriodic,
               boolean isPersisted, long intervalMillis, long flexMillis, long initialBackoffMillis,
               int backoffPolicy, boolean importantWhileForeground, boolean prefetch) {
    this.jobId = jobId;
    this.service = service;
    this.extras = extras;
    this.transientExtras = transientExtras;
    this.clipData = clipData;
    this.clipGrantFlags = clipGrantFlags;
    this.constraintFlags = constraintFlags;
    this.triggerContentUris = triggerContentUris;
    this.triggerContentUpdateDelay = triggerContentUpdateDelay;
    this.triggerContentMaxDelay = triggerContentMaxDelay;
    this.hasEarlyConstraint = hasEarlyConstraint;
    this.hasLateConstraint = hasLateConstraint;
    this.networkType = networkType;
    this.networkRequest = networkRequest;
    this.networkDownloadBytes = networkDownloadBytes;
    this.networkUploadBytes = networkUploadBytes;
    this.minLatencyMillis = minLatencyMillis;
    this.maxExecutionDelayMillis = maxExecutionDelayMillis;
    this.isPeriodic = isPeriodic;
    this.isPersisted = isPersisted;
    this.intervalMillis = intervalMillis;
    this.flexMillis = flexMillis;
    this.initialBackoffMillis = initialBackoffMillis;
    this.backoffPolicy = backoffPolicy;
    this.importantWhileForeground = importantWhileForeground;
    this.prefetch = prefetch;
}
 
Example #26
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 #27
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 #28
Source File: FadeInNetworkImageView.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(21)
@Override
public void setImageUrl(String url, ImageLoader imageLoader) {
    mShowLocal = TextUtils.isEmpty(url);
    if (mDiskCache.get(url) == null && !OnlineAccessVerifier.check(getContext())) {
        this.setImageBitmap(null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final ConnectivityManager cm = (ConnectivityManager)
                    getContext().getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            networkCallback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    new CoverArtLoader((MainActivity) FadeInNetworkImageView.this.getActivity()).execute(mLyrics);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && networkCallback != null)
                        try {
                            cm.unregisterNetworkCallback(networkCallback);
                        } catch (IllegalArgumentException ignored) {
                        }
                }
            };
            NetworkRequest request = new NetworkRequest.Builder()
                    .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
            cm.registerNetworkCallback(request, networkCallback);
        }
        defaultShown = true;
    } else {
        super.setImageUrl(url, imageLoader);
        if (!TextUtils.isEmpty(url))
            defaultShown = false;
    }
}
 
Example #29
Source File: RequirementsWatcher.java    From Telegram with GNU General Public License v2.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 #30
Source File: NetworkChangeNotifierAutoDetect.java    From cronet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Registers networkCallback to receive notifications about networks
 * that satisfy networkRequest.
 * Only callable on Lollipop and newer releases.
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
void registerNetworkCallback(
        NetworkRequest networkRequest, NetworkCallback networkCallback, Handler handler) {
    // Starting with Oreo specifying a Handler is allowed.  Use this to avoid thread-hops.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mConnectivityManager.registerNetworkCallback(
                networkRequest, networkCallback, handler);
    } else {
        mConnectivityManager.registerNetworkCallback(networkRequest, networkCallback);
    }
}