Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Display Bluetooth Paired Devices Programmatically in Android?
Next article icon

How to Programmatically Enable/Disable Bluetooth in Android?

Last Updated : 14 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

In Android Phone, it is very much easy to enable/disable Bluetooth by using the Bluetooth icon, but have you wondered how to do this task programmatically in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. 

Sample GIF

Steps for Programmatically Enable/Disable Bluetooth 

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Working with the AndroidManifest.xml file

Go to the AndroidManifest.xml file and add two user-permissions: BLUETOOTH and BLUETOOTH_ADMIN.

<uses-permission android:name=”android.permission.BLUETOOTH”/>

<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/>

Below is the code for the AndroidManifest.xml file. 

XML

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wifi">
  
    <!--Put the permissions between the manifest and application opening tags-->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
  
</manifest>
                      
                       

Step 3: Working with the activity_main.xml file

When the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Create a Button that changes the state of the Bluetooth on click and a TextView that shows the status of the Bluetooth state. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML

<?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">
  
    <!--Changes the state of Bluetooth on button click-->
    <Button
        android:id="@+id/BtBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Click" />
  
    <!--Displays the state of Bluetooth on button click-->
    <TextView
        android:id="@+id/BtTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/BtBtn"
        android:layout_centerHorizontal="true"
        android:hint="Bluetooth Status"
        android:textSize="30sp" />
  
</RelativeLayout>
                      
                       

Step 4: Working with the MainActivity.kt file

In the MainActivity.kt file, declare the Button, TextView, and a Bluetooth adapter (refer to the codes). While setting the on click listeners to the button, use the Bluetooth adapter to enable or disable the Bluetooth. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin

import android.bluetooth.BluetoothAdapter
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Declaring Button and TextView
        // 1. Changes the state of Bluetooth on button click
        // 2. Shows the state of the Bluetooth
        val btnBt = findViewById<Button>(R.id.BtBtn)
        val tvBt = findViewById<TextView>(R.id.BtTv)
  
        // Declaring Bluetooth adapter
        val mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
  
        // On button Click
        btnBt.setOnClickListener {
  
            // Enable or disable the Bluetooth and display
              // the state in Text View
            if (mBluetoothAdapter.isEnabled) {
                mBluetoothAdapter.disable()
                tvBt.text = "Bluetooth is OFF"
            } else {
                mBluetoothAdapter.enable()
                tvBt.text = "Bluetooth is ON"
            }
        }
    }
}
                      
                       

Output: Run on Physical Device

https://media.geeksforgeeks.org/wp-content/uploads/20200919172559/2020_09_19_17_25_04_trim.mp4


Next Article
How to Display Bluetooth Paired Devices Programmatically in Android?
author
aashaypawar
Improve
Article Tags :
  • Android
  • Kotlin
  • Android Projects

Similar Reads

  • How to Programmatically Enable/Disable Wi-Fi in Android?
    In Android Phone, it is very much easy to enable/disable WiFi by using the WiFi icon, but have you wondered how to do this task programmatically in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project usin
    3 min read
  • How to Display Bluetooth Paired Devices Programmatically in Android?
    Bluetooth's technology is a high-speed, low-powered wireless technology link designed to connect devices such as phones or other portable equipment. It has a specification (IEEE 802.15.1) for low-power radio communications to link computers, phones, and other network devices over a short distance in
    5 min read
  • How to Disable Dark Mode Programmatically in Android?
    In this article, we will learn how to disable Dark Mode programmatically in Android. Changing the theme of your app is a simple task that includes changing the code in the XML file. Step by Step Implementation Step 1: Create a New Project in Android Studio Create a new project by clicking on the fil
    2 min read
  • How to Enable/Disable Button in Android?
    The Enable/Disable Feature is used in many Android apps so the basic use of that feature is to prevent the user from clicking on a button until they will add all the required fields that have been asked. We are considering an example of email and password if the user has entered the email and passwo
    3 min read
  • How to Fetch Device ID in Android Programmatically?
    The android Device ID is a unique code, string combinations of alphabets and numbers, given to every manufactured android device. This code is used to identify and track each android device present in the world. In Android, the Device ID is typically related to the Google Play Services and is most c
    3 min read
  • How to Check the Battery Level in Android Programmatically?
    Sometimes, it is useful to determine the current battery level. One may choose to reduce the rate of your background updates if the battery charge is below a certain level. But one cannot continuously monitor the battery state. In general, the impact of constantly monitoring the battery level has a
    2 min read
  • How to Vibrate a Device Programmatically in Android?
    Hepatic feedback are also considered when it comes to user experience. So in this discussion, it's been discussed various types of haptics or the types of vibration of the device. For example, click haptics or long-press button haptics. There five different types of vibration modes in haptic feedbac
    7 min read
  • How to Detect Touch Event on Screen Programmatically in Android?
    Detecting a touch confirms that the screen is fully functional. Responding to touch is something that a developer deals with. As Android devices have a touch-based input, things are programmed upon application of touch. For explicitly calling methods within the application, a touch action must be re
    5 min read
  • How to Make Bluetooth Discoverable to Other Devices in Android?
    In Android devices, Bluetooth is a communication network protocol that allows devices to connect wirelessly to exchange data with other Bluetooth devices. In general, we can make use of Bluetooth API to implement Bluetooth functionalities, such as enabling or disabling Bluetooth, searching for avail
    5 min read
  • How to Get Current Default Language of Android Device Programmatically?
    Smartphones seem to be predicting and showing us results from what we think in our minds. If you think of traveling, you shall soon expect something related to it in your device's feed. This is the next level of technology, where data helps in developing businesses. The software collects personal da
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences