In this first part of Bluetooth series examples for Android we are going to see how Bluetooth service is switched on and off on a device. For this example we are going to use actual device for testing, because there is more complicated to test it on emulator.
The first thing we need to do is to add ButterKnife library in to our project, that is strongly recommended so we can bind the views form our XML in to our java code. This is done in build.gradle file in app folder in our project
1 2 |
implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' |
The next thing we need to do is add permissions in our AndroidManifest.xml file like:
1 2 3 |
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> |
Then we need to add Switch button so we can turn the Bluetooth on the device on and off:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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" tools:context=".MainActivity"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="@string/bluetooth_example" android:textColor="@color/black" android:textSize="20sp" /> <Switch android:id="@+id/switchButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@string/bluetooth" android:textSize="20sp" /> </RelativeLayout> |
Here is the Main Activity where in onCreate method we add our previously imported library ButterKnife with .bind() method. We must initialize the BluetoothAdapter class (default Bluetooth adapter class in Android) with BluetoothAdapter.getDefaultAdapter(); After that we check if the bswitch is ON or OFF to start the Bluetooth service or stop it. That is happening in BluetoothManager that we will see it later in this example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public class MainActivity extends AppCompatActivity { BluetoothAdapter mBluetoothAdapter; @BindView(R.id.switchButton) Switch switchButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { BluetoothManager.turnOn(mBluetoothAdapter, MainActivity.this); } else { BluetoothManager.turnOff(mBluetoothAdapter, MainActivity.this); } } }); } } |
And the end there is most important part of this example the actial turning on and off the bluetooth service on the device. In this example there are two ways of turning the Bluetooth, with system permission or without it. The first one is commented code, and do the same thing as the second one but with a pop up requesting users permission. These are public static methods, so we dont need to create an object from BluetoothManager class in our MainActivity.
The turnOn() method (with system permissions) accepts BluetoothAdapter and the Activity object as a parameters. They are passed from Main Activity where we have instantiated the BluetoothAdapter and it is passed here, and the Activity object is passed so we can create a Intent. After the intent is being created that calls for enabling the bloototh service to be active, we declare REQUEST code so we can start the activity for result. We are activating the call for the service with .enable() method on the bluetooth adapter.
For turnOn() method without permissions we use only .enable() method on the bluetooth adapter.
The turnOff() method is simpler. We just check if the bluetooth adapter is active, and if it is, we turn it off with .disable() method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public class BluetoothManager { public static void turnOn(BluetoothAdapter btAdapter, Activity activity) { // Turning bluetooth ON with system permission // if (!btAdapter.isEnabled()) { // Intent intentBtEnabled = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // // The REQUEST_ENABLE_BT constant passed to startActivityForResult() is a locally defined integer (which must be greater than 0), that the system passes back to you in your onActivityResult() // // implementation as the requestCode parameter. // int REQUEST_ENABLE_BT = 1; // activity.startActivityForResult(intentBtEnabled, REQUEST_ENABLE_BT); // } else { // Toast.makeText(activity, "Bluetooth already enabled", Toast.LENGTH_SHORT).show(); // } // Turning bluetooth ON without system permission if (!btAdapter.isEnabled()) { btAdapter.enable(); Toast.makeText(activity, "Bluetooth turned ON", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, "Bluetooth already enabled", Toast.LENGTH_SHORT).show(); } } public static void turnOff(BluetoothAdapter btAdapter, Activity activity) { if (btAdapter.isEnabled()) { btAdapter.disable(); Toast.makeText(activity, "Bluetooth turned OFF", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(activity, "Bluetooth already disabled", Toast.LENGTH_SHORT).show(); } } } |
Here are the string resources used in this project:
1 2 3 |
<string name="app_name">BluetoothScan</string> <string name="bluetooth_example">Bluetooth scan example</string> <string name="bluetooth">Bluetooth</string> |