1 /*
2  * Copyright (C) 2020 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 com.android.settings.testutils;
18 
19 import android.content.ContentResolver;
20 import android.content.Context;
21 import android.provider.Settings;
22 import android.util.Log;
23 
24 import androidx.test.core.app.ApplicationProvider;
25 
26 import org.junit.rules.ExternalResource;
27 
28 /** A test rule that is used to manager the Airplane Mode resource for testing. */
29 public final class AirplaneModeRule extends ExternalResource {
30 
31     private static final String TAG = "AirplaneModeRule";
32 
33     private Context mContext;
34     private ContentResolver mContentResolver;
35     private boolean mBackupValue;
36     private boolean mShouldRestore;
37 
38     @Override
before()39     protected void before() throws Throwable {
40         mContext = ApplicationProvider.getApplicationContext();
41         mContentResolver = mContext.getContentResolver();
42     }
43 
44     @Override
after()45     protected void after() {
46         if (!mShouldRestore) {
47             return;
48         }
49         Log.d(TAG, "Restore Airplane Mode value:" + mBackupValue);
50         Settings.Global.putInt(mContentResolver, Settings.Global.AIRPLANE_MODE_ON,
51                 mBackupValue ? 1 : 0);
52     }
53 
setAirplaneMode(boolean enable)54     public void setAirplaneMode(boolean enable) {
55         if (enable == isAirplaneModeOn()) {
56             return;
57         }
58         if (!mShouldRestore) {
59             mShouldRestore = true;
60             mBackupValue = !enable;
61             Log.d(TAG, "Backup Airplane Mode value:" + mBackupValue);
62         }
63         Log.d(TAG, "Set Airplane Mode enable:" + enable);
64         Settings.Global.putInt(mContentResolver, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
65     }
66 
isAirplaneModeOn()67     public boolean isAirplaneModeOn() {
68         return Settings.Global.getInt(mContext.getContentResolver(),
69             Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
70     }
71 }
72