Home | History | Annotate | Download | only in controllers
      1 /*
      2  * Copyright 2017 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package androidx.work.impl.constraints.controllers;
     18 
     19 import static androidx.work.NetworkType.CONNECTED;
     20 
     21 import android.content.Context;
     22 import android.os.Build;
     23 import android.support.annotation.NonNull;
     24 
     25 import androidx.work.impl.constraints.NetworkState;
     26 import androidx.work.impl.constraints.trackers.Trackers;
     27 import androidx.work.impl.model.WorkSpec;
     28 
     29 /**
     30  * A {@link ConstraintController} for monitoring that any usable network connection is available.
     31  * <p>
     32  * For API 26 and above, usable means that the {@link NetworkState} is validated, i.e.
     33  * it has a working internet connection.
     34  * <p>
     35  * For API 25 and below, usable simply means that {@link NetworkState} is connected.
     36  */
     37 
     38 public class NetworkConnectedController extends ConstraintController<NetworkState> {
     39     public NetworkConnectedController(Context context, OnConstraintUpdatedCallback callback) {
     40         super(Trackers.getInstance(context).getNetworkStateTracker(), callback);
     41     }
     42 
     43     @Override
     44     boolean hasConstraint(@NonNull WorkSpec workSpec) {
     45         return workSpec.constraints.getRequiredNetworkType() == CONNECTED;
     46     }
     47 
     48     @Override
     49     boolean isConstrained(@NonNull NetworkState state) {
     50         if (Build.VERSION.SDK_INT >= 26) {
     51             return !state.isConnected() || !state.isValidated();
     52         } else {
     53             return !state.isConnected();
     54         }
     55     }
     56 }
     57