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.network; 18 19 import android.content.Context; 20 import android.net.EthernetManager; 21 import android.net.TetheringManager; 22 import android.os.Handler; 23 import android.os.Looper; 24 import android.text.TextUtils; 25 26 import androidx.lifecycle.Lifecycle; 27 import androidx.lifecycle.OnLifecycleEvent; 28 29 import com.android.internal.annotations.VisibleForTesting; 30 31 /** 32 * This controller helps to manage the switch state and visibility of ethernet tether switch 33 * preference. 34 */ 35 public final class EthernetTetherPreferenceController extends TetherBasePreferenceController { 36 37 private final String mEthernetRegex; 38 private final EthernetManager mEthernetManager; 39 @VisibleForTesting 40 EthernetManager.Listener mEthernetListener; 41 EthernetTetherPreferenceController(Context context, String preferenceKey)42 public EthernetTetherPreferenceController(Context context, String preferenceKey) { 43 super(context, preferenceKey); 44 mEthernetRegex = context.getString( 45 com.android.internal.R.string.config_ethernet_iface_regex); 46 mEthernetManager = (EthernetManager) context.getSystemService(Context.ETHERNET_SERVICE); 47 } 48 49 @OnLifecycleEvent(Lifecycle.Event.ON_START) onStart()50 public void onStart() { 51 mEthernetListener = new EthernetManager.Listener() { 52 @Override 53 public void onAvailabilityChanged(String iface, boolean isAvailable) { 54 new Handler(Looper.getMainLooper()).post(() -> updateState(mPreference)); 55 } 56 }; 57 mEthernetManager.addListener(mEthernetListener); 58 } 59 60 @OnLifecycleEvent(Lifecycle.Event.ON_STOP) onStop()61 public void onStop() { 62 mEthernetManager.removeListener(mEthernetListener); 63 mEthernetListener = null; 64 } 65 66 @Override shouldEnable()67 public boolean shouldEnable() { 68 String[] available = mCm.getTetherableIfaces(); 69 for (String s : available) { 70 if (s.matches(mEthernetRegex)) { 71 return true; 72 } 73 } 74 return false; 75 } 76 77 @Override shouldShow()78 public boolean shouldShow() { 79 return !TextUtils.isEmpty(mEthernetRegex); 80 } 81 82 @Override getTetherType()83 public int getTetherType() { 84 return TetheringManager.TETHERING_ETHERNET; 85 } 86 } 87