Android and bluetooth headset

Android Bluetooth headset connection

I am new to Android Platform. I am working with an application requires integration of Bluetooth. The requirement is instead of manually connecting and disconnecting a Bluetooth headset(HSP profile),Connection and disconnection should be possible within the application.Is it possible to connect and disconnect the device in Android devices running OS 4.2 ,4.3 and 4.4.If any one has a solution for this issue,Please advise me for the same.

1 Answer 1

It is possible, but sometimes not that simple.

To connect, start by checking whether or not the device you are running on has BT support at all:

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter==null) < // device not support BT >

If not — gracefully disable the BT portion of your app and move on.

If supported, check whether or not it is currently enabled (remember, the user can turn BT on & off as with other communication channels):

boolean isEnabled = bluetoothAdapter.isEnabled(); // Equivalent to: getBluetoothState() == STATE_ON 

And, if not enabled, allow the user to turn it on by firing an ACTION_REQUEST_ENABLE intent:

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, ENABLE_BT_CODE); 

Once you are clear in terms of availability, perform lookup for the specific device you aim for. It is always a good idea to start with the bonded device list maintained by Android:

Set bondedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device: pairedDevices) < if (device is the one we look for) < return device; >> 

If not, you will need to issue a BT discovery command.

Discovery must never be performed on the UI thread, so please spawn a thread (use AsyncTask, Executer, etc. to do the work).

Discovery should not be performed when a BT connection operation is still taking place. The impact on the device resources will be too high.

Start by setting your discovery receiver:

discoveryReceiver = new BroadcastReceiver() < private boolean wasFound = false; @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); System.out.println(action); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) < discoveryStatus = STARTED; >else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < discoveryStatus = FINISHED; >else if (BluetoothDevice.ACTION_FOUND.equals(action)) < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device is what we look for) < stopDiscovery(context); >> > >; IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothDevice.ACTION_FOUND); context.registerReceiver(discoveryReceiver, filter); 

And follow with a start off command:

boolean started = bluetoothAdapter.startDiscovery(); //async call! if (!started) < // log error >

Once you find your device, you will then need to create a dedicated BT socket:

BluetoothSocket clientSocket = null; try < if (secureMode == SECURE) < clientSocket = device.createRfcommSocketToServiceRecord(serviceUuid); >else < // INSECURE clientSocket = device.createInsecureRfcommSocketToServiceRecord(serviceUuid); >if (clientSocket == null) < throw new IOException(); >> catch (IOException e) < // log error >

Followed by connect command:

 clientSocket.connect(context); 

Once connect returns, you can transmit data back & forth the way you do with sockets and when done:

The above depicts the general flow. In many cases your work will be harder:

You will use different socket generation methods for secure vs. insecure BT modes. You will use different methods to interrogate the device for supported UUIDs. You may also sometimes have to resort to reflection to activate hidden services e.g. getUuids() for Android < ver 15. And the list goes on.

Читайте также:  Микронаушник для экзамена bluetooth

It makes sense, especially for a beginner, to use a tool for this job.

My favorite (I am biased, I wrote it..) is BTWiz which will encapsulate the above flow from you and will also provide you with a simple interface for async IO. Feel free to try it out.

Источник

Правильное подключение Bluetooth-наушников на Android

Как подключить Блютуз наушники к телефону на Андроид

На сегодняшний день беспроводное подключение различных устройств к телефону на платформе Android является нормой для большинства пользователей. В чисто гаджетов, предоставляющих такие возможности, входят и наушники, требующие от смартфона наличия Bluetooth. Дальше мы опишем процедуру подключения подобной периферии с учетом разных моделей.

Подключение Bluetooth-наушников на Android

Большинство моделей наушников, выпускаемых в низком и среднем ценовом диапазоне, можно подключить к Android-устройству по единой инструкции в несколько шагов. Дополнительные действия при этом требуются лишь в некоторых случаях и зачастую не стоят упоминания.

  1. Нажмите кнопку включения на гарнитуре и, если нужно, активируйте функцию Bluetooth отдельно. Чаще всего достаточно просто включить наушники. Кнопка включения на Bluetooth-наушниках
  2. В разделе «Настройки» на телефоне перейдите на страницу «Bluetooth» и воспользуйтесь ползунком «Включить». На разных моделях смартфонов действия могут отличаться. Включение функции Bluetooth в настройках на Android

Примечание: Название периферии и более точные действия для включения Bluetooth можно узнать из инструкции в комплекте.

Настоящая инструкция, хоть и рассчитана на обычные Bluetooth-наушники, выпускаемые малоизвестными компаниями, а не крупными брендами, все же подходит и для более дорогостоящей периферии. Одним из таких примеров служит фирменная гарнитура от Apple.

AirPods

Некоторые модели беспроводных наушников, такие как AirPods, вполне совместимы с Android-устройствами, но в процессе соединения имеют несколько отличий от представленной инструкции. К примеру, в случае уже заявленной периферии от Apple потребуется заранее поместить гарнитуру в зарядный кейс, убедиться в наличии достаточного количества заряда и только после этого переходить к подключению.

Пример беспроводных наушников AirPods для телефона

Наушники с NFC-чипом

Этот вид Bluetooth-гарнитуры отличается от ранее приведенных примеров, так как позволяет подключаться значительно быстрее, используя встроенный NFC-чип. Единственным условием для работы подобных наушников выступает наличие соответствующего чипа не только в гарнитуре, но и на Android-устройстве.

  1. Первым делом включите наушники при помощи соответствующей кнопки, расположенной на корпусе. Обычно процедура включения функции NFC указана в стандартной инструкции производителя. Пример Bluetooth-наушников с NFC-чипом
  2. На телефоне откройте системное приложение «Настройки» и в разделе «Беспроводные сети» включите функцию «NFC». Ее расположение, равно как и в случае с Bluetooth, может отличаться на разных смартфонах. Подробнее: Как включить NFC на AndroidВключение функции NFC в Настройках на Android
  3. Следующим и последним шагом поднесите телефон к наушникам и подтвердите подключение на экране. Разновидность запроса напрямую зависит от производителя гарнитуры и Android-устройства.

Подобная гарнитура имеют высокую цену и встречается крайне редко, поэтому акцентировать внимание на инструкции стоит только при наличии подобных наушников.

Заключение

В завершение данной статьи стоит упомянуть о несовместимости некоторых моделей наушников и Android-устройств по причине низкой версии Bluetooth у телефона. Проблема встречается не так часто и обычно не распространяется на гарнитуру. Однако во избежание несовместимости все же рекомендуем заранее до покупки ознакомиться с требованиями периферии, сверившись с характеристиками смартфона.

Источник

Как подключить мобильный телефон к гарнитуре Bluetooth

В создании этой статьи участвовала наша опытная команда редакторов и исследователей, которые проверили ее на точность и полноту.

Читайте также:  Sven sps 615 black 2x10w bluetooth sv 013707

Команда контент-менеджеров wikiHow тщательно следит за работой редакторов, чтобы гарантировать соответствие каждой статьи нашим высоким стандартам качества.

Количество источников, использованных в этой статье: 8. Вы найдете их список внизу страницы.

Количество просмотров этой статьи: 50 386.

Bluetooth-гарнитуры очень популярны у современных и мобильных людей. Подключив Bluetooth-гарнитуру к телефону, вы можете делать и принимать звонки без необходимости держать устройство в руке, что весьма удобно при управлении автомобилем, совершении покупок или простой пробежке. Если ваш телефон оснащен Bluetooth-модулем, подключите его к Bluetooth-гарнитуре, чтобы упростить пользование устройством.

Подготовка Bluetooth-гарнитуры

Изображение с названием Pair a Cell Phone to a Bluetooth Headset Step 1

Зарядите гарнитуру. Следует зарядить как телефон, так и гарнитуру, чтобы разряд аккумулятора не привел к прерыванию процесса сопряжения.

Изображение с названием Pair a Cell Phone to a Bluetooth Headset Step 2

  • В большинстве случаев включите гарнитуру, а затем в течение нескольких секунд удерживайте нажатой многофункциональную кнопку (то есть кнопку, которую вы нажимаете, чтобы ответить на звонок). Сначала светодиод будет мигать, сигнализируя, что гарнитура включена (не отпускайте кнопку!), а через несколько секунд светодиод будет мигать разными цветами (как правило, красным и синим, но встречаются и другие цвета). Мигающий светодиод означает, что гарнитура находится в режиме сопряжения.
  • Если ваша гарнитура оснащена переключателем «Вкл/Выкл» (On/Off), передвиньте его в положение «Вкл» (On), прежде чем нажать и удерживать многофункциональную кнопку. [1] X Источник информации

Изображение с названием Pair a Cell Phone to a Bluetooth Headset Step 3

Расположите гарнитуру недалеко от телефона. Для сопряжения оба устройства должны находиться близко друг к другу. Для получения наилучших результатов расстояние между устройствами не должно превышать 1,5 м. [2] X Источник информации

Источник

Android connect to a paired bluetooth headset

I want to simulate the action of going throgh Settings->Wireless->Bluetooth and connect a paired bluetooth headset programmatically. I’ve done some search in Stackoverflow and Google, both indicating that there is no solution available before API level 11. However, I’m interested in working it out by peeking in the source code of bluetooth implementation of Android. The problem is that I’m not aware of which specific source code I should review. Any suggestions? Many thanks.

4 Answers 4

After days of struggling, I’ve now managed to do it, cheers 🙂

  1. Add android.bluetooth.IBluetoothA2dp.aidl in your /src dir of your app;
  2. Add this private method in your code:
private IBluetoothA2dp getIBluetoothA2dp() < IBluetoothA2dp ibta = null; try < Class c2 = Class.forName("android.os.ServiceManager"); Method m2 = c2.getDeclaredMethod("getService", String.class); IBinder b = (IBinder) m2.invoke(null, "bluetooth_a2dp"); Log.d("Felix", "Test2: " + b.getInterfaceDescriptor()); Class c3 = Class.forName("android.bluetooth.IBluetoothA2dp"); Class[] s2 = c3.getDeclaredClasses(); Class c = s2[0]; // printMethods(c); Method m = c.getDeclaredMethod("asInterface", IBinder.class); m.setAccessible(true); ibta = (IBluetoothA2dp) m.invoke(null, b); >catch (Exception e)
private void testBluetoothA2dp(BluetoothDevice device) < // TODO Auto-generated method stub // TODO Auto-generated method stub IBluetoothA2dp ibta = getIBluetoothA2dp(); try < Log.d("Felix", "Here: " + ibta.getSinkPriority(device)); ibta.connectSink(device); >catch (RemoteException e) < // * TODO Auto-generated catch block e.printStackTrace(); >

I’m not able to provide references of these code since I’ve spent lots of time googling, checking out stackoverflow, and reviewing Android source code, but failed to keep track of sources. Many thanks to you guys in Stackoverflow 🙂

Hi there, I am also trying to connect a A2dp bluetooth headset to Android. I have already successfully paired with the bluetooth device without user interface as show in: stackoverflow.com/questions/3462968/…
But even using your code after pairing I still cannot connect to the headset (no error on Android 4.0.3 — Galaxy Note 1 ). Any idea ?

Читайте также:  Сгорел блютуз в ноутбуке

OK, I got this updated to support Honeycomb and up. You need to add new functions to the interface. I did that here:

interface IBluetoothA2dp < boolean connectSink(in BluetoothDevice device); // Pre API 11 only boolean disconnectSink(in BluetoothDevice device); // Pre API 11 only boolean connect(in BluetoothDevice device); // API 11 and up only boolean disconnect(in BluetoothDevice device); // API 11 and up only boolean suspendSink(in BluetoothDevice device); // all boolean resumeSink(in BluetoothDevice device); // all BluetoothDevice[] getConnectedSinks(); // change to Set<>once AIDL supports, pre API 11 only BluetoothDevice[] getNonDisconnectedSinks(); // change to Set<> once AIDL supports, int getSinkState(in BluetoothDevice device); boolean setSinkPriority(in BluetoothDevice device, int priority); // Pre API 11 only boolean setPriority(in BluetoothDevice device, int priority); // API 11 and up only int getPriority(in BluetoothDevice device); // API 11 and up only int getSinkPriority(in BluetoothDevice device); // Pre API 11 only boolean isA2dpPlaying(in BluetoothDevice device); // API 11 and up only 

Then you need to check the API version before calling functions in this interface. Here is my example:

 if (android.os.Build.VERSION.SDK_INT < 11) < IBluetoothA2dp ibta = getIBluetoothA2dp(); try < Log.d(LOG_TAG, "Here: " + ibta.getSinkPriority(device)); if (ibta != null) ibta.connectSink(device); >catch (Exception e) < Log.e(LOG_TAG, "Error " + e.getMessage()); >> else < IBluetoothA2dp ibta = getIBluetoothA2dp(); try < Log.d(LOG_TAG, "Here: " + ibta.getPriority(device)); if (ibta != null) ibta.connect(device); >catch (Exception e) < Log.e(LOG_TAG, "Error " + e.getMessage()); >> 

Hope this helps. I was able to get the same app to work with both interfaces.

I tried this on Android 4.2 and following line returns null. It was working on 4.1, any ideas ?

IBinder b = (IBinder) m2.invoke(null, "bluetooth_a2dp"); 

Did you add: android.bluetooth.IBluetoothA2dp.aidl in your /src dir of your app; in your /src directory?

this is KIND of related to the connect/reconnect issue (the ANSWER being an apple script) ..

i just bought an android htc one V and am using it as a hotspot via the app PdaNet (installed both on my phone and my mac os 10.5.8 ppc laptop).

I can’t seem to get the hotspot tethering working via wifi or usb but it DOES work well with BLUETOOTH! only problem is the connection only lasts up to 2 minutes to 40 minutes (looking at it now ha, a record) and i have to reconnect manually, which only takes 2 seconds but it’d be nice if the Network aspect of my mac could AUTO reconnect.

my cell is not the problem as it’s sending out a constant signal (although i could be losing signal temporarily from my cell, which is normal connection stuff) .. the problem is having my laptop auto RE-connect. my laptop and htc one v DO remain paired, there’s just no AUTO-RECONNECT on the laptop end.

i wish i knew apple scripts bcs then i could maybe write an apple script that AUTO-RECONNECTS a lost bluetooth connection .. or maybe a widget could do this? if so i’d have it made in the shade as bluetooth tethering is working NICELY.

i was hoping this would help both myself and others searching for the same answers .. if you keep this thread open i could return later with some possible apple script solutions (which i will have to quickly learn) .. thanks -marcus

Источник

Оцените статью
Adblock
detector