In this post, we will see how to enable or disable Bluetooth in android programmatically.
It is very simple to enable or disable bluetooth from android code.
For enabling Bluetooth:
It is very simple to enable or disable bluetooth from android code.
For enabling Bluetooth:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); adapter.enable();
For disabling Bluetooth:
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); adapter.disable();
So you can enable or disable Bluetooth using BluetoothAdapter class.
You need to add extra permissions in AndroidManifest.xml to enable or disable Bluetooth.
Source code:
Step 1 :
Create an android application project named “EnableDisableBluetoothApp”.
Step 2:
Add following permissions in AndoridManifest.xml.
Go to app -> src -> main -> AndroidManifest.xml and add above permissions. AndroidManifest.xml will look like below xml.
Step 3 :
Change res ->layout -> activity_main.xml as below:
Step 4:
Change src/main/packageName/MainActivity.java as below:
package com.java2blog.enabledisablebluetoothapp;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.java2blog.enabledisablebluetoothapp.R;
public class MainActivity extends AppCompatActivity {
ToggleButton toggleButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting toggle button and textView from activity_main
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
textView = (TextView) findViewById(R.id.textView);
// Put listener on toggle button
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
textView.setText("Bluetooth is ON");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();
} else {
textView.setText("Bluetooth is OFF");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.disable();
}
}
});
// For initial setting
if (toggleButton.isChecked()) {
textView.setText("Bluetooth is ON");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.enable();
} else {
textView.setText("Bluetooth is OFF");
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.disable();
}
}
}
Step 5:
Run the app
When you run the app, you will get below screen:

When you click on toggle button, you will get below screen:

love u man thank u so much.