From c79e14a2fdfccada2fc1ac81eb908e5011e4247d Mon Sep 17 00:00:00 2001 From: Yiyi Shen Date: Mon, 17 Mar 2025 16:18:32 +0800 Subject: [PATCH] Move setScanMode to background thread to avoid ANR Test: atest Bug: 397951829 Flag: EXEMPT small fix Change-Id: I6450fc9cef1cfea3bb940e5d37a552df1f75dd23 --- .../bluetooth/AlwaysDiscoverable.java | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/com/android/settings/bluetooth/AlwaysDiscoverable.java b/src/com/android/settings/bluetooth/AlwaysDiscoverable.java index 2ac4a18c645..5ea99ae194e 100644 --- a/src/com/android/settings/bluetooth/AlwaysDiscoverable.java +++ b/src/com/android/settings/bluetooth/AlwaysDiscoverable.java @@ -24,6 +24,8 @@ import android.content.IntentFilter; import androidx.annotation.VisibleForTesting; +import com.android.settingslib.utils.ThreadUtils; + /** Helper class, intended to be used by an Activity, to keep the local Bluetooth adapter in * discoverable mode indefinitely. By default setting the scan mode to * BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE will time out after some time, but some @@ -55,10 +57,12 @@ public class AlwaysDiscoverable extends BroadcastReceiver { mContext.registerReceiver(this, mIntentFilter, Context.RECEIVER_EXPORTED_UNAUDITED); mStarted = true; - if (mBluetoothAdapter.getScanMode() - != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { - mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE); - } + ThreadUtils.postOnBackgroundThread(() -> { + if (mBluetoothAdapter.getScanMode() + != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { + mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE); + } + }); } public void stop() { @@ -67,7 +71,8 @@ public class AlwaysDiscoverable extends BroadcastReceiver { } mContext.unregisterReceiver(this); mStarted = false; - mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE); + ThreadUtils.postOnBackgroundThread( + () -> mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE)); } @Override @@ -76,9 +81,11 @@ public class AlwaysDiscoverable extends BroadcastReceiver { if (action != BluetoothAdapter.ACTION_SCAN_MODE_CHANGED) { return; } - if (mBluetoothAdapter.getScanMode() - != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { - mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE); - } + ThreadUtils.postOnBackgroundThread(() -> { + if (mBluetoothAdapter.getScanMode() + != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { + mBluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE); + } + }); } }