Friday, April 10, 2015

How to receive Bluetooth broadcast intents

This post about receiving Bluetooth broadcast intents, written for a series about creating a Bluetooth home screen widget, seemed worthwhile standalone, so here it is, in three steps.

Step 1. Create a BroadcastReceiver to receive Bluetooth events

Create a class that extends BroadcastReceiver. Android Studio has a wizard that will do this for you. Right-click on the path where you want the file created in the Project pane. Select New > Other > Broadcast Receiver. In the wizard, name the class (here named BluetoothReceiver for our widget project) and Android Studio will create this for you:

Code created by Android Studio's Broadcast Receiver wizard

The circled method, onReceive(), will be called whenever we get one of the Bluetooth Intents.

Later in the post, we'll add code to onReceive() to process these intents.

Now, we'll turn to the manifest, which needs to be updated to let Android know we want to receive broadcast intents, where they should be delivered, and which ones we want to receive.

Step 2. Tell Android we want to receive Bluetooth broadcast intents

Our BroadcastReceiver will not receive Bluetooth broadcast intents until we tell Android, in AndroidManifest.xml, three things:

  a) that we want permission to receive these intents (via a <uses-permission> element)
  b) where they should be delivered (via a <receiver> element)
  c) which ones we want (via <intent-filter> elements)

Here's how we do it.

a. Request permission to receive Bluetooth intents

We need to request permission to receive Bluetooth's broadcast intents. We can do this by adding the following line (a <uses-permission> element) to AndroidManifest.xml, within the <manifest> element and outside of the <application> element.

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

b. Tell Android where to deliver them (our BroadcastReceiver)

When we created the BroadcastReceiver, Android Studio did us the favor of adding a <receiver> element to AndroidManifest.xml which declares our new broadcast receiver:

BroadcastReceiver entry in AndroidManifest.xml, added by Android Studio. We still next a uses-permission and intent-filter elements though.

c. Declare which broadcast intents we want to receive

If you take a look at the <intent-filter> section of the AndroidManifest.xml file from the Bluetooth Intent Logger project, which listens for documented Bluetooth broadcast intents and logs them, you'll see over 20 Bluetooth intent actions that you could register for.

Consider building and installing Bluetooth Intent Logger on your Android device. It will let you see first-hand the Bluetooth events that are generated when you play with Bluetooth by writing them to logcat as they occur, and give you a better idea of what you can get via broadcast intents. I wrote it to figure out what intents I should be receiving when my code isn't working as expected. The source is available on Github.

For our Bluetooth Home Screen Widget app (your needs may differ), we're interested some intents that tell us about state changes in the Bluetooth system: 

  • android.bluetooth.adapter.action.STATE_CHANGED tells us when Bluetooth is turning on or off.
  • android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED tells us when a device has gaining or losing its status as the media audio device.
  • android.bluetooth.device.action.BOND_STATE_CHANGED tells us when a device has paired or unpaired.

The resulting AndroidManifest.xml

The parts discussed above, that are necessary for receiving certain Bluetooth broadcast intents, are highlighted.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.phonedev.bluetoothrouter" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
        android:theme="@style/AppTheme" >
        <receiver android:name=".MusicAppWidget" >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />

                android:resource="@xml/music_app_widget_info" />
            android:exported="true" >
                <action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
                <action android:name="android.bluetooth.device.action.BOND_STATE_CHANGED" />
                <action android:name="android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED" />

Step 3. Process incoming intents in the BroadcastReceiver's onReceive()

Finally, we'll add code to onReceive() to handle the incoming intents. We're essentially receiving messages from Bluetooth here, and some of them will trigger actions in our code. For now, we'll delegate those actions to other methods that we'll fill in later.

With a few log messages, you can verify that you are receiving the intents by exercising Bluetooth and watching what appears using adb logcat.

To reduce the log noise, filter out all but the Bluetooth log messages using (from a shell)

$ adb logat -s BluetoothReceiver

where BluetoothReceiver is the tag provided as the first argument of the Log.d() calls, below.

package com.phonedev.bluetoothrouter;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class BluetoothReceiver extends BroadcastReceiver {
    public BluetoothReceiver() {

    private static final String TAG = "BluetoothReceiver";    // a tag for logging
    private static final int FAIL = -1;                       // default if extra key not found

     * Receives certain Bluetooth broadcast intents.
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();            // Get intent's action string
        Bundle extras = intent.getExtras();            // Get all the Intent's extras
        if (extras == null) return;                    // All intents of interest have extras.

        switch (action) {
            case "android.bluetooth.adapter.action.STATE_CHANGED": {
                bluetoothStateChanged(extras.getInt("android.bluetooth.adapter.extra.STATE", FAIL));
            case "android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED": {
                        extras.getInt("android.bluetooth.profile.extra.STATE", FAIL),
                        (BluetoothDevice) extras.get("android.bluetooth.device.extra.DEVICE"));
            case "android.bluetooth.device.action.BOND_STATE_CHANGED": {
                        extras.getInt("android.bluetooth.device.extra.BOND_STATE", FAIL),
                        (BluetoothDevice) extras.get("android.bluetooth.device.extra.DEVICE"));

     * Handles changes in widget operation when Bluetooth state changes.
     * @param state one of the BluetoothAdapter on/off and transitioning states
    private void bluetoothStateChanged(int state) {
        switch (state) {
            case BluetoothAdapter.STATE_OFF:
            case BluetoothAdapter.STATE_TURNING_ON:
            case BluetoothAdapter.STATE_ON:
            case BluetoothAdapter.STATE_TURNING_OFF:
                // TODO: trigger changes in how widget handles clicks and displays devices
                Log.d(TAG, "Bluetooth adapter state changed to: " + state);

     * Handles changes in widget operation when a device's A2DP connection state changes
     * @param device the BluetoothDevice whose A2DP connection state has changed
     * @param state the new state, one of the BluetoothProfile connection and transitioning states
    private void a2dpStateChanged(int state, BluetoothDevice device) {
        switch (state) {
            case BluetoothProfile.STATE_DISCONNECTED:
            case BluetoothProfile.STATE_CONNECTING:
            case BluetoothProfile.STATE_CONNECTED:
            case BluetoothProfile.STATE_DISCONNECTING:
                // TODO: trigger changes in how widget handles clicks and displays this device
                Log.d(TAG, "Bluetooth A2DP state changed to " + state + " for " + device.getName());

     * Handles changes in widget operation when a device's bond state changes
     * @param device the BluetoothDevice whose bond state has changed
     * @param state the new state, one of the BluetoothDevice BOND and transitioning states
    private void bondStateChanged(int state, BluetoothDevice device) {
        switch (state) {
            case BluetoothDevice.BOND_NONE:
            case BluetoothDevice.BOND_BONDING:
            case BluetoothDevice.BOND_BONDED:
                // TODO: trigger changes in how widget handles clicks and displays this device
                Log.d(TAG, "Bluetooth bond state changed to " + state + " for " + device.getName());


  1. whats about MainActivity. Please share code of MainActivity

  2. I am trying to have my application start once a connection to a specific bluetooth-device is established. Is there any way to do this? So when I turn bluetooth to "on" on my PC i have registered with the Android-Phone before i would like the application to start, say for example in the MainActivity?

    1. Were you able to figure it out? I'm stuck on the same issue

  3. A national job bank for broadcast graduates is, which lists several types of broadcasting job categories.PaxFax FaxBroadcast

  4. 96% of Americans with internet access have made an online purchase in their life, 80% in the past month alone.account based marketing

  5. It is an exceptionally key marketing stage that achieves diverse societies, ages, religion, genders, areas, premiums and such, along these lines it makes it the ideal vehicle to reach and focus on the correct group of onlookers and make add up to progress. get Instagram followers

  6. For instance Companies spend significant time in housekeeping give benefits only to different associations, instead of individual buyers.

  7. Proficient and Experienced SEO Services Can Be the Difference Between You and Your Competitors
    SEO Hrvatska

  8. Straightforward dialect and "genuine worldlike" good manners are the bases for the best of methodologies. It is once in a while increasingly productive to begin a dialog that may appear miles from your item and its crusade destinationsInfo Here

  9. The answer email ought to be explicit to your inquiry dislike any business pamphlet.

    pixel marketing

  10. A SEO marketing organization ordinarily gives all Internet marketing arrangements. Thus, don't give that SEO a chance to label trick you - search engine optimization expert you will get full administration from these organizations. Here is the thing that you can anticipate:

  11. This comment has been removed by the author.

  12. Traditional media such as radio, TV, and print had been around long enough that there were thousands of case studies one could study the success or failures of individual campaigns web developer nuneaton

  13. As the market one of the most dubious books, and now the Internet mogul's a year still comprise a significant buzz all over the place.adfluencer

  14. During the course, you would come across the benefits of online marketing over traditional marketing.ronald banilov

  15. SEO is extraordinarily essential to the accomplishment of your web based showcasing endeavors, along these lines, a great deal of advertisers execute different SEO devices including nearby SEO apparatuses, some of which can be found for nothing, so as to track, gauge and investigate their SEO endeavors.Webdesign

  16. It can be pretty challenging for someone with no real audience to get even a handful of video views, let alone thousands. That's why it's not embarrassing to ask for help when you feel like you're being crushed under the weight of trying to keep up with the things that come with trying to build a presence for yourself on social media. If that's the same case for you, don't worry at all. We got you. With SociFan's brand-new tool, it's possible to buy Twitter video views for your content!

  17. Are you looking for a fast way to grow your Instagram page? Do you want to gain free instagram followers.

  18. Most web designers may relate this to most exceedingly terrible model in a web design process.Webdesign

  19. You can purchase all of the social media like TikTok, YouTube, Instagram likes views, comments, followers, subscribers and so many greater from India's No.-1 promoting website with a money-back guarantee, steady method, genuine service, 24/7 help, and many more offers.

  20. A significant capacity of MyBo was to interface individuals who knew each other outside of the battle to associate, for example, is done on Facebook.smm panel

  21. Plainly when website admins employ a site improvement SEO master, they have a superior possibility of expanding their SEO administrations. SEO lead generation

  22. Thanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article
    by cloudi5 is the Web design company in coimbatore

  23. The article was absolutely fantastic! Lot of great information which can be helpful in some or the other way. Keep updating the blog, looking forward for more contents.
    By Cognex
    AWS Training in Chennai

  24. Excellent, what a webpage it is! This web site provides valuable
    information to us, keep it up. get 10k Instagram followers.!!

  25. Some 'SEOs' do site design improvement and some web index control. Obviously, it is totally showcased as SEO. Website laten maken

  26. Most SEO organizations get paid whether your site gets any

  27. VideoPad Registration Code with Crack really is a handy utility by having an interface is split into sections this kind of as media lists, results, transitions, files, clips, video tracks, audio tracks, lined tracks, which can make all the things seem a bit more difficult to function.

  28. The Chandigarh call girls are supposed to be the most charming selections in the whole area whom you would like to avail in for the instances of love.

    Visit Our Website:-
    Chandigarh call girls
    Chandigarh Independent Escorts

  29. VIP Escorts in Chandigarh are offering only the best and most pretty girls who are avid to show you they can exceed your expectation and that they are much than just a lovely face.

    Visit us now:_
    VIP Escorts in Chandigarh
    Escorts in Chandigarh

  30. Thanks for sharing this piece of information. I really enjoyed it. keep up the good work. Buy Instagram Followers India

  31. Get the hottest Escorts in Chandigarh for ultimate sexual fun with bold and beautiful ladies. Call to book Call Girls in Chandigarh available 24x7 hours.
    Chandigarh Escort Service |

  32. This post is a pool of information. The readers are quite impressed after reading this impressive post. Digital Agency In India

  33. Thank you for helping people get the information they need. Great stuff as usual. Keep up the great work!
    VideoPad Video Editor Crack

  34. I think this is one of the most important information for me.
    And i am glad reading your article. But should remark on few general things, the web
    site style is ideal, the articles is really nice
    Avast Antivirus Crack 2021

  35. I'm keen on the various blog posts, When i severely preferred, I'd prefer specifics about the item, due to the fact it is superb., Best wishes concerning producing.
    buying YouTube Views
    buy cheap YouTube Views

    The 5-megapixel depth-of-field camera blurs the background, and the 5-megapixel macro camera focuses on very close objects.

    For the M51, Samsung has included a 32-megapixel Sony IMX 616 selfie camera that captures high quality photos.
    Check the Galaxy M51 in terms of software

  37. Do you want to create and lead youtube channel about it? I think you can do it quite easy. From here you can get subscribers for your profile

  38. Hi,

    Hope you are doing fine!

    My name is Haseeb, I work for an online marketing agency.

    I came across your site ( today and got impressed with the regular updates on it.

    Just wanted to know if you do accept guest posts on your site?

    Also, if you could let me know the price per in-content text link placement on an existing blog post of your site?

    Looking forward to hearing from you soon.



  39. Recuva pro Keygen is free of charge windows utility software which has a quick scan for swift data recovery it's also possible to enable a deep scan. A quick scan normally takes a small volume of time though in deep scan will take a lot longer. Even though in each modes the process continues to be smooth .and the PC stays stable.

  40. On the off chance that you draw in with them, this supports future commitment which lead to connections, trust, and deals! read full report

  41. Thank you for sharing!
    Really a good post.
    Now You Can Easily Download Every Crack Software From Here*
    Please visit!
    I think you are looking for this software. visit our website:-
    Benvista PhotoZoom Pro
    Roxio MyDVD
    Sonarworks Reference

  42. Moreover, the presence of low maintenance SEOs just as the section of amateurs into the market might have let to the low paces of turnover because of low activity limit. MavericksMedia

  43. Hundreds of Instagram Followers, Likes, and Views – Real Users, Real Accounts, and Quick Delivery! Boost Your Instagram Presence in Minutes! buy instagram followers

  44. Thank you for sharing. This is Very Usefull post. Thanks For Post which have lot of knowledge

    mastercam Crack
    Adobe Media Encoder Crack
    GlarySoft Malware Hunter Pro Crack

  45. I guess I am the only one who came here to share my very own experience. Guess what!? I am using my laptop for almost the past 2 years, but I had no idea of solving some basic issues. I do not know how to Crack But Thankfully, I recently visited a website named Cracked Fine
    Mathworks Matlab Crack
    Debut Video Capture Crack
    Wise Care Pro Crack

  46. So nice I am enjoying for that post as for u latest version of this Security tool Available.
    Recuva Pro Crack

  47. Thanks for Sharing such an amazing article. Keep working... Your Site is very nice, and it's very helping us.. this post is unique and interesting, thank you for sharing this awesome information Smadav Pro Crack

  48. This sites gives very interesting information about off season camping,really i like this which is so much beneficial to us,keep sharing such kind of information,Thanks for sharing.
    Enscape 3D
    Advanced SystemCare Pro
    Car Mechanic Simulator
    Tenorshare 4uKey

  49. Thanks for sharing such an amazing post. Great Work. Love visiting your blog. I would like to thank you for sharing this post. Really Happy to Read. Easy Cut Studio With Crack

  50. Casino Near Me - Mapyro
    Find Casino Near 보령 출장샵 Me, Nevada, United States - Find your 상주 출장안마 way around the casino, find where 여수 출장마사지 everything is located 진주 출장샵 with the best 강원도 출장마사지 reviews and real traveler

  51. Hi, The content is very informative and amazing. Thank you for sharing such a good articles. We are also Website Designing Company in Gurgaon. Dixinfotech in web-related services includes Website Designing, Web Development, E-commerce Website Development, etc. They provide affordable website designing services and their cost is very low They develop customized websites for the clients as per the requirement of the business. They provide the best services.

    IntelliJ IDEA Crack is not about only the editor: it helps you stay productive when dealing with other aspects as well: e.g.
    Clip Studio Paint EX Crack is a full-featured drawing software specifically designed to allow comic and manga artists to effortlessly discover their ideas and swiftly create,
    SpyHunter Crack is a Windows application designed to look for, detect, eliminate and stop malware and potentially unwanted programs (PUPs) and other items.
    SketchUp Pro Crack is really an advanced software in the field of 3D graphics and designs. It is furnished with great icons, as well as the amazing toolbars that make it interesting and fairly simple even for CAD beginners.
    MyCleanPC Crack is an easy to utilize, lightweight piece of programming for cleaning undesirable documents from your PC, upgrading Windows fire-up times, and guaranteeing your PC moves along as planned.

  53. Thank you so much for sharing this amazing information

  54. Hello Dear, I love your site. Many thanks for the shared this informative and interesting post with us.
    Stellar Repair for Excel Crack

  55. Thanks for sharing this post. Your work is amazing. You can also check out PicPick Professional Crack for Free. You can also visit the Website
    PhpStorm Crack
    Camtasia Studio Crack

  56. Virtual payroll-services that specializes in helping small businesses and Professional Services Firms. The online bookkeeping service helps small businesses with bookkeeping, payroll, and tax needs.

  57. best online game for free in US and EBA - TopCleo
    The rules of the online 카지노사이트 game 바카라사이트 allow players to make wagers while taking advantage of various offers and promotions from the developer.

  58. Your work is greatly appreciated. My favorite blog

  59. Great post, thanks for sharing valuable information, keep us posted more. Servicenow Training in Pune

  60. Bulk WhatsApp marketing can be a game-changer for businesses looking to connect with their audience on a personal level. The power of reaching a large number of potential customers through this platform cannot be underestimated. It allows for direct communication and engagement, which is key in today's digital age.

  61. Excellent information in this Post. Keep it up. Thanks for sharing Love to read it, Waiting For More new Update and I Already Read your Recent Post its Great Thanks
    Angula r-Js Training institute in Hyderabad


  62. wtfast Crack
    thanks for sharing nice and informative data Keep it up