В этом уроке мы узнаем как узнать поддерживает ли устройство Bluetooth и научимся узнавать включен Bluetooth или нет.
В приведенном ниже примере мы будем вызывать метод startActivityForResult () с Intent’ом BluetoothAdapter.ACTION_REQUEST_ENABLE , для проверки соединения, когда пользователь нажмет на кнопку.
Создайте новый проект и вставьте следующий код в main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.androidbluetooth.MainActivity">
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/enablebt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enable BlueTooth">
</LinearLayout>
А вот код MainActivity:
public class MainActivity extends Activity {
TextView textInfo;
Button buttonEnableBT;
BluetoothAdapter bluetoothAdapter;
final static int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textInfo = (TextView)findViewById(R.id.info);
buttonEnableBT = (Button)findViewById(R.id.enablebt);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
textInfo.setText("BlueTooth not supported in this device");
buttonEnableBT.setEnabled(false);
}else{
if (bluetoothAdapter.isEnabled()) {
buttonEnableBT.setEnabled(false);
textInfo.setText("BlueTooth enabled");
}else{
buttonEnableBT.setEnabled(true);
textInfo.setText("BlueTooth disabled, click button to turn on BlueTooth.");
}
}
buttonEnableBT.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_ENABLE_BT){
if(resultCode==RESULT_OK){
Toast.makeText(MainActivity.this, "BlueTooth Turned On", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this, "Cancelled", Toast.LENGTH_LONG).show();
}
}
if (bluetoothAdapter.isEnabled()) {
buttonEnableBT.setEnabled(false);
textInfo.setText("BlueTooth enabled");
}else{
buttonEnableBT.setEnabled(true);
textInfo.setText("BlueTooth disabled, click button to turn on BlueTooth.");
}
}
}
Пропишем права доступа к Bluetooth в манифесте:
<uses-permission android:name="android.permission.BLUETOOTH">
Запускаем приложение и проверяем:


