Created
May 18, 2024 01:05
-
-
Save Lerie82/701c1f78190bb319bb04dd874760783e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* AI generated */ | |
import android.bluetooth.BluetoothAdapter; | |
import android.bluetooth.BluetoothDevice; | |
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class BluetoothHelper { | |
private Context context; | |
private BluetoothAdapter bluetoothAdapter; | |
private List<BluetoothDevice> deviceList; | |
private BluetoothListener listener; | |
public BluetoothHelper(Context context) { | |
this.context = context; | |
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); | |
deviceList = new ArrayList<>(); | |
registerBluetoothReceiver(); | |
} | |
public void setListener(BluetoothListener listener) { | |
this.listener = listener; | |
} | |
private void registerBluetoothReceiver() { | |
context.registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND)); | |
} | |
private final BroadcastReceiver receiver = new BroadcastReceiver() { | |
public void onReceive(Context context, Intent intent) { | |
String action = intent.getAction(); | |
if (BluetoothDevice.ACTION_FOUND.equals(action)) { | |
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); | |
deviceList.add(device); | |
if (listener != null) { | |
listener.onDeviceFound(deviceList); | |
} | |
} | |
} | |
}; | |
public void startDiscovery() { | |
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) { | |
bluetoothAdapter.startDiscovery(); | |
} | |
} | |
public void stopDiscovery() { | |
if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) { | |
bluetoothAdapter.cancelDiscovery(); | |
} | |
} | |
public interface BluetoothListener { | |
void onDeviceFound(List<BluetoothDevice> devices); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment