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
17package androidx.work.impl.constraints.controllers;
18
19import static androidx.work.NetworkType.NOT_ROAMING;
20
21import android.content.Context;
22import android.os.Build;
23import android.support.annotation.NonNull;
24import android.util.Log;
25
26import androidx.work.impl.constraints.NetworkState;
27import androidx.work.impl.constraints.trackers.Trackers;
28import androidx.work.impl.model.WorkSpec;
29
30/**
31 * A {@link ConstraintController} for monitoring that the network connection is not roaming.
32 */
33
34public class NetworkNotRoamingController extends ConstraintController<NetworkState> {
35    private static final String TAG = "NetworkNotRoamingCtrlr";
36
37    public NetworkNotRoamingController(Context context, OnConstraintUpdatedCallback callback) {
38        super(Trackers.getInstance(context).getNetworkStateTracker(), callback);
39    }
40
41    @Override
42    boolean hasConstraint(@NonNull WorkSpec workSpec) {
43        return workSpec.constraints.getRequiredNetworkType() == NOT_ROAMING;
44    }
45
46    /**
47     * Check for not-roaming constraint on API 24+, when JobInfo#NETWORK_TYPE_NOT_ROAMING was added,
48     * to be consistent with JobScheduler functionality.
49     */
50    @Override
51    boolean isConstrained(@NonNull NetworkState state) {
52        if (Build.VERSION.SDK_INT < 24) {
53            Log.d(TAG, "Not-roaming network constraint is not supported before API 24, "
54                    + "only checking for connected state.");
55            return !state.isConnected();
56        }
57        return !state.isConnected() || !state.isNotRoaming();
58    }
59}
60