public class MainActivity extends AppCompatActivity {
private static final int REQ_CODE_BT = 1001;
private BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = mBluetoothAdapter.getDefaultAdapter();
// Обработчик OnClick
View.OnClickListener OnClick = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bluetooth_button:
if (bluethoothButton.isChecked())
enableBluetooth();
else
disableBluetooth();
break;
}
}
};
bluethoothButton.setOnClickListener(OnClick);
}
@Override
protected void onResume() {
super.onResume();
stateBluethooth();
}
// Если блютуз не поддерживаеться
private void noSupportedBluetooth() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.noSupportedBluethooth, Toast.LENGTH_LONG).show();
}
}
// Включаем блютуз
private void enableBluetooth() {
if (!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQ_CODE_BT);
}
}
// Проверяем состояние блютуз
private void stateBluethooth(){
if (mBluetoothAdapter.isEnabled()) {
bluethoothButton.setChecked(true);
}
}
// Выключаем блютуз
private void disableBluetooth() {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
}
}
您可以通过以下方式搜索设备:
获取配对设备列表如下所示: