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.
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.
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:
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" />
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="http://schemas.android.com/apk/res/android"
package="com.phonedev.bluetoothrouter" >
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name=".MusicAppWidget" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/music_app_widget_info" />
</receiver>
<receiver
android:name=".BluetoothReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<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" />
</intent-filter>
</receiver>
</application>
</manifest>
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 @Override /** * 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)); break; } case "android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED": { a2dpStateChanged( extras.getInt("android.bluetooth.profile.extra.STATE", FAIL), (BluetoothDevice) extras.get("android.bluetooth.device.extra.DEVICE")); break; } case "android.bluetooth.device.action.BOND_STATE_CHANGED": { bondStateChanged( extras.getInt("android.bluetooth.device.extra.BOND_STATE", FAIL), (BluetoothDevice) extras.get("android.bluetooth.device.extra.DEVICE")); break; } } } /** * 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()); } } }
whats about MainActivity. Please share code of MainActivity
ReplyDeleteGreat Article android based projects
DeleteJava Training in Chennai
Project Center in Chennai
Java Training in Chennai
projects for cse
The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training
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?
ReplyDeleteWere you able to figure it out? I'm stuck on the same issue
DeleteA national job bank for broadcast graduates is CareerPage.org, which lists several types of broadcasting job categories.PaxFax FaxBroadcast
ReplyDelete96% of Americans with internet access have made an online purchase in their life, 80% in the past month alone.account based marketing
ReplyDeleteIt 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
ReplyDeleteFor instance Companies spend significant time in housekeeping give benefits only to different associations, instead of individual buyers.
ReplyDeleteEmeryeps.com
Proficient and Experienced SEO Services Can Be the Difference Between You and Your Competitors
ReplyDeleteSEO Hrvatska
Nice Tutorial.Transmitterreviews.com
ReplyDeleteStraightforward 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
ReplyDeleteThe answer email ought to be explicit to your inquiry dislike any business pamphlet.
ReplyDeletepixel marketing
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:
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteTraditional 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
ReplyDeleteAs 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
ReplyDeleteDuring the course, you would come across the benefits of online marketing over traditional marketing.ronald banilov
ReplyDeleteSEO 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
ReplyDeletehttps://www.socifan.com/buy-twitter-video-views 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!
ReplyDeleteAre you looking for a fast way to grow your Instagram page? Do you want to gain free instagram followers.
ReplyDeleteAre you a YouTuber? Do you want to increase your audience then visit here for youtube marketing, youtube viewership boost and for likes.This is the world's best portal for youtube marketing and promotions.
ReplyDeleteGreat news for social media enthusiast and content creators.. If you want to increase your real time followers then go through https://www.ytviews.in and get full support and guarantee.
ReplyDeleteGreat news for social media enthusiast and content creators from our side. If you want to increase your real time youtube views, subscribers, followers etc.. then visit https://www.ytviews.in/ and get full support and guarantee
ReplyDeleteBuy youtube views from india's no.1 website https://www.tubeviews.in/ , and submit an easy order on the website TUBEVIEWS
ReplyDeleteCreatorshala is india's largest community of content creators, if you u are a blogger,influencer and youtuber, you can create your creators account on https://www.creatorshala.com/
ReplyDeleteBuy Facebook Likes - 100% REAL Facebook Ads Method Used!
ReplyDeletehttps://www.liftlikes.com/buy-facebook-likes/
Want to Buy Facebook Likes? Give us a try. We deliver 100% real facebook likes with No drop guarantee. Buy Facebook Likes Now!
Most web designers may relate this to most exceedingly terrible model in a web design process.Webdesign
ReplyDeleteYou 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 https:www.ytviews.in/ with a money-back guarantee, steady method, genuine service, 24/7 help, and many more offers.
ReplyDeleteA 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
ReplyDeletePlainly when website admins employ a site improvement SEO master, they have a superior possibility of expanding their SEO administrations. SEO lead generation
ReplyDeleteThanks For Sharing The Information The Information Shared Is Very Valuable Please Keep Updating Us Time Just Went On Reading The article
ReplyDeleteby cloudi5 is the Web design company in coimbatore
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.
ReplyDeleteBy Cognex
AWS Training in Chennai
Excellent, what a webpage it is! This web site provides valuable
ReplyDeleteinformation to us, keep it up. get 10k Instagram followers.!!
Some 'SEOs' do site design improvement and some web index control. Obviously, it is totally showcased as SEO. Website laten maken
ReplyDeleteNice blog, i found some useful information from this article, thanks for sharing the great information.
ReplyDeletejobs in devops
soft skills and communication skills
tableau certification cost
how to improve english speaking
blue prism interview questions and answers pdf
blue prism interview question and answer
javascript coding questions and answers
buy Instagram followers 10k.
ReplyDeleteDr. Vivek Galani is a leading expert in skin and hair. At hair transplant clinic in Surat Skin Care, Cosmetic Laser, Hair Transplant & Slimming Center, Dr. Galani offers the most advanced cosmetic and dermatologic care treatments. The clinic uses advanced FUE methods to produce high-quality hair transplants.
ReplyDeleteMost SEO organizations get paid whether your site gets any rankings.Webdesign-seo-antwerpen.be
ReplyDeleteVideoPad 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. https://freeprosoftz.com/videopad-video-editor-crack/
ReplyDeleteShreeja Health Care is leading manufacturer of Mini oil Maker Machine. Shreeja Oil Extraction Machine is able to extract oil from various seeds like peanuts, Coconut, Sesame, Soybean, macadamia nuts, walnuts, sunflower seeds, vegetable seeds flaxseed et
ReplyDeleteThe 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.
ReplyDeleteVisit Our Website:-
Chandigarh call girls
Chandigarh Independent Escorts
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.
ReplyDeleteVisit us now:_
VIP Escorts in Chandigarh
Escorts in Chandigarh