首先控制蓝牙开关的逻辑很简单,bluetoothAdapter.disable();
就可以关闭。这里需要用到android.bluetooth.BluetoothAdapter;
--- a/packages/apps/Settings/res/xml/connected_devices.xml
+++ b/packages/apps/Settings/res/xml/connected_devices.xml
@@ -20,6 +20,11 @@
android:key="connected_devices_screen"
android:title="@string/connected_devices_dashboard_title">
+ <SwitchPreference
+ android:key="toggle_bluetooth"
+ android:title="@string/bluetooth_switch_title"
+ android:summary="@string/bluetooth_switch_summary"/>
+
<com.android.settings.slices.SlicePreference
android:key="bt_nearby_slice"
android:title="@string/summary_placeholder"
这里我曾经尝试写新的controller去控制最后没成功,然后又催的比较急。就粗暴一点直接写在Fragment里面了。
--- a/packages/apps/Settings/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java
+++ b/packages/apps/Settings/src/com/android/settings/connecteddevice/ConnectedDeviceDashboardFragment.java
@@ -28,6 +28,11 @@ import com.android.settings.dashboard.DashboardFragment;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.slices.SlicePreferenceController;
import com.android.settingslib.search.SearchIndexable;
+import androidx.preference.SwitchPreferenceCompat;
+import androidx.preference.SwitchPreference;
+import androidx.preference.Preference;
+import android.bluetooth.BluetoothAdapter;
+import android.os.Bundle;
@SearchIndexable(forTarget = SearchIndexable.ALL & ~SearchIndexable.ARC)
public class ConnectedDeviceDashboardFragment extends DashboardFragment {
@@ -38,6 +43,7 @@ public class ConnectedDeviceDashboardFragment extends DashboardFragment {
static final String KEY_CONNECTED_DEVICES = "connected_device_list";
@VisibleForTesting
static final String KEY_AVAILABLE_DEVICES = "available_device_list";
+ static final String KEY_TOGGLE_BLUETOOTH = "toggle_bluetooth";
@Override
public int getMetricsCategory() {
@@ -77,6 +83,37 @@ public class ConnectedDeviceDashboardFragment extends DashboardFragment {
: null);
}
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ SwitchPreference bluetoothSwitch = findPreference(KEY_TOGGLE_BLUETOOTH);
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (bluetoothSwitch != null) {
+ bluetoothSwitch.setChecked(bluetoothAdapter.isEnabled());
+ bluetoothSwitch.setOnPreferenceChangeListener(
+ new Preference.OnPreferenceChangeListener() {
+ @Override
+ public boolean onPreferenceChange(Preference preference, Object newValue) {
+ boolean isChecked = (Boolean) newValue;
+ BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
+ if (bluetoothAdapter != null) {
+ if (isChecked) {
+ if (!bluetoothAdapter.isEnabled()) {
+ bluetoothAdapter.enable();
+ }
+ } else {
+ if (bluetoothAdapter.isEnabled()) {
+ bluetoothAdapter.disable();
+ }
+ }
+ }
+ return true;
+ }
+ }
+ );
+ }
+ }
+
一开始是写在里面自带的一个onAttach函数里面,但是发现没效果,可能是正因为函数执行的时候界面还为加载完毕所以没有获取到里面的元素。所以我自己重写了onCreate方法,写在这里面。