Bluetooth paired device code

How to connect with paired Bluetooth device programmatic in Android?

I am developing an application where I have to connect to Bluetooth paired device. These two devices are paired with each other. Now when I try to connect with paired device it stuck with the connecting mode dialog. Log shows that it successfully connect but does not dismiss the dialog. Here is my code snippet. Main.java

import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.Settings; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class Main extends Activity < protected static final String TAG = "TAG"; private static final int REQUEST_CONNECT_DEVICE = 1; private static final int REQUEST_ENABLE_BT = 2; Button mScan; BluetoothAdapter mBluetoothAdapter; private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); @Override public void onCreate(Bundle mSavedInstanceState) < super.onCreate(mSavedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.main); mScan = (Button) findViewById(R.id.Scan); mScan.setOnClickListener(new View.OnClickListener() < public void onClick(View mView) < mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) < Toast.makeText(Main.this, "DeviceHasNoSupport", 2000).show(); >else < if (!mBluetoothAdapter.isEnabled()) < Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >else < ListPairedDevices(); Intent connectIntent = new Intent(Main.this, DeviceListActivity.class); startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE); >> > >); >// onCreate public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent) < super.onActivityResult(mRequestCode, mResultCode, mDataIntent); switch (mRequestCode) < case REQUEST_CONNECT_DEVICE: if (mResultCode == Activity.RESULT_OK) < Bundle mExtra = mDataIntent.getExtras(); String mDeviceAddress = mExtra.getString("DeviceAddress"); Log.v(TAG, "Coming incoming address " + mDeviceAddress); BluetoothDevice mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress); pairToDevice(mBluetoothDevice); Log.v(TAG, "pairToDeviceCalled"); >break; case REQUEST_ENABLE_BT: if (mResultCode == Activity.RESULT_OK) < ListPairedDevices(); Intent connectIntent = new Intent(Main.this, DeviceListActivity.class); startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE); >else < Toast.makeText(Main.this, "BTNotEnabled", 2000).show(); >break; > > private void ListPairedDevices() < SetmPairedDevices = mBluetoothAdapter.getBondedDevices(); if (mPairedDevices.size() > 0) < for (BluetoothDevice mDevice : mPairedDevices) < Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress()); >> > private void pairToDevice(BluetoothDevice nBluetoothDevice) < Log.v(TAG, "InsidepairToDeviceCalled"); openSocket(nBluetoothDevice); Log.v(TAG, "LeavingpairToDeviceCalled"); >private void openSocket(BluetoothDevice nBluetoothDevice) < try < Log.v(TAG, "InsideOpenSockedCalled"); final ProgressDialog dialog = new ProgressDialog(this); final ConnectRunnable connector = new ConnectRunnable(nBluetoothDevice, dialog); Log.v(TAG, "InsideOpenSockedConnecterCalled"); ProgressDialog.show(this, "Connecting. ", nBluetoothDevice.getName() + " : " + nBluetoothDevice.getAddress(), true, true, new OnCancelListener() < public void onCancel(DialogInterface dialog) < connector.cancel(); >>); new Thread(connector).start(); > catch (IOException ex) < Log.d(TAG, "Could not open bluetooth socket", ex); >> private class ConnectRunnable implements Runnable < private final ProgressDialog dialog; private final BluetoothSocket socket; public ConnectRunnable(BluetoothDevice device, ProgressDialog dialog) throws IOException < socket = device.createRfcommSocketToServiceRecord(applicationUUID); this.dialog = dialog; >public void run() < try < Log.v(TAG, "InsideRunnableCalled"); mBluetoothAdapter.cancelDiscovery(); socket.connect(); Log.v(TAG, "InsideRunnableSocketConnectCalled"); >catch (IOException connectException) < Log.d(TAG, "Could not connect to socket", connectException); closeSocket(socket); return; >Log.v(TAG, "Connected"); dismissDialog(dialog); closeSocket(socket); > public void cancel() < try < socket.close(); >catch (IOException e) < Log.d(TAG, "Canceled connection", e); >> > private void dismissDialog(final Dialog dialog) < runOnUiThread(new Runnable() < public void run() < dialog.dismiss(); Log.v(TAG, "DialogClosed"); >>); > private void closeSocket(BluetoothSocket nOpenSocket) < try < nOpenSocket.close(); Log.v(TAG, "SockectClosed"); >catch (IOException ex) < Log.d(TAG, "Could not close exisiting socket", ex); >> @Override public boolean onKeyDown(int mKeyCode, KeyEvent mKeyEvent) < if ((!(android.os.Build.VERSION.SDK_INT >android.os.Build.VERSION_CODES.DONUT) && mKeyCode == KeyEvent.KEYCODE_BACK && mKeyEvent.getRepeatCount() == 0)) < onBackPressed(); >return super.onKeyDown(mKeyCode, mKeyEvent); > public void onBackPressed() < finish(); >> 
import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class DeviceListActivity extends Activity < protected static final String TAG = "TAG"; private BluetoothAdapter mBluetoothAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; @Override protected void onCreate(Bundle mSavedInstanceState) < super.onCreate(mSavedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); setResult(Activity.RESULT_CANCELED); mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); ListView mPairedListView = (ListView) findViewById(R.id.paired_devices); mPairedListView.setAdapter(mPairedDevicesArrayAdapter); mPairedListView.setOnItemClickListener(mDeviceClickListener); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set mPairedDevices = mBluetoothAdapter.getBondedDevices(); if (mPairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice mDevice : mPairedDevices) < mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress()); >> else < String mNoDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(mNoDevices); >> @Override protected void onDestroy() < super.onDestroy(); if (mBluetoothAdapter != null) < mBluetoothAdapter.cancelDiscovery(); >> private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewmAdapterView, View mView, int mPosition, long mLong) < mBluetoothAdapter.cancelDiscovery(); String mDeviceInfo = ((TextView) mView).getText().toString(); String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17); Log.v(TAG, "Device_Address " + mDeviceAddress); Bundle mBundle = new Bundle(); mBundle.putString("DeviceAddress", mDeviceAddress); Intent mBackIntent = new Intent(); mBackIntent.putExtras(mBundle); setResult(Activity.RESULT_OK, mBackIntent); finish(); >>; > 
06-16 13:46:08.640 19062 19062 E CachedBluetoothDevice: updating profiles for $ $ S A \/ A N $ $ 06-16 13:46:08.640 19062 19062 V CachedBluetoothDevice: opp classbits != uuid 06-16 13:46:08.640 19062 19062 V CachedBluetoothDevice: Class: 5a0204 06-16 13:46:08.640 19062 19062 V CachedBluetoothDevice: UUID: 06-16 13:46:08.640 19062 19062 V CachedBluetoothDevice: 00001101-0000-1000-8000-00805f9b34fb 06-16 13:46:08.667 19091 19091 V TAG : PairedDevices: $ $ S A \/ A N $ $ 00:1D:3B:05:B4:D5 06-16 13:46:10.582 19091 19091 V TAG : Device_Address 00:1D:3B:05:B4:D5 06-16 13:46:10.597 19091 19091 V TAG : Coming incoming address 00:1D:3B:05:B4:D5 06-16 13:46:10.597 19091 19091 V TAG : InsidepairToDeviceCalled 06-16 13:46:10.597 19091 19091 V TAG : InsideOpenSockedCalled 06-16 13:46:10.718 19091 19091 V TAG : InsideOpenSockedConnecterCalled 06-16 13:46:10.789 19091 19091 V TAG : LeavingpairToDeviceCalled 06-16 13:46:10.789 19091 19091 V TAG : pairToDeviceCalled 06-16 13:46:10.800 19091 19128 V TAG : InsideRunnableCalled 06-16 13:46:13.730 19091 19128 V TAG : InsideRunnableSocketConnectCalled 06-16 13:46:13.730 19091 19128 V TAG : Connected 06-16 13:46:13.730 19091 19128 V TAG : SockectClosed 06-16 13:46:13.734 19091 19091 V TAG : DialogClosed 

Where am going wrong? Anybody who has successfully configured Bluetooth with processing dialog, Please give me a hand. Thanks.

Читайте также:  Bluetooth and personal area networks

Источник

Android Bluetooth List Paired Devices with Examples

In android, Bluetooth is a communication network protocol, which allows devices to connect wirelessly to exchange the data with other Bluetooth devices.

Generally, in android applications by using Bluetooth API’s we can implement Bluetooth functionalities, such as enable or disable a Bluetooth, searching for available Bluetooth devices, connecting with the devices and managing the data transfer between devices within the range.

In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our applications. To know more about BluetoothAdapter, check this Android Bluetooth with Examples.

Android Bluetooth List Paired Devices

By using BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices list.

Following is the code snippet to get all paired devices with name and MAC address of each device.

// Get paired devices.
Set pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0 ) // There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
>
>

If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.

As we discussed in previous tutorial Android Bluetooth with Examples, we need to set Bluetooth permissions in our android manifest file like show below to use Bluetooth features in our android applications.

Following is the example of getting the list of available Bluetooth paired devices on button click in android applications.

Android List Bluetooth Paired Devices Example

Create a new android application using android studio and give names as BluetoothListPairedDevicesExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Читайте также:  Iphone bluetooth headphones with microphone

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :orientation= «vertical» >
< Button
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :id= «@+id/btnGet»
android :text= «Get Paired Devices»
android :layout_marginLeft= «130dp»
android :layout_marginTop= «200dp»/>
< ListView
android :id= «@+id/deviceList»
android :layout_width= «match_parent»
android :layout_height= «wrap_content» >

Now open your main activity file MainActivity.java from \java\com.tutlane.bluetoothexample path and write the code like as shown below

MainActivity.java

package com.tutlane.bluetoothlistpaireddevicesexample;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;

public class MainActivity extends AppCompatActivity private ListView lstvw ;
private ArrayAdapter aAdapter ;
private BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btn = (Button)findViewById(R.id. btnGet );
btn.setOnClickListener( new View.OnClickListener() @Override
public void onClick(View v) if ( bAdapter == null ) Toast.makeText(getApplicationContext(), «Bluetooth Not Supported» ,Toast. LENGTH_SHORT ).show();
>
else Set pairedDevices = bAdapter .getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()> 0 ) for (BluetoothDevice device: pairedDevices) String devicename = device.getName();
String macAddress = device.getAddress();
list.add( «Name: » +devicename+ «MAC Address: » +macAddress);
>
lstvw = (ListView) findViewById(R.id. deviceList );
aAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout. simple_list_item_1 , list);
lstvw .setAdapter( aAdapter );
>
>
>
>);
>
>

If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.

As discussed, we need to set Bluetooth permissions in android manifest file (AndroidManifest.xml) to access Bluetooth features in android applications. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below

Читайте также:  Управление подключенными устройствами bluetooth

AndroidManifest.xml

If you observe above code, we added required Bluetooth permissions in manifest file to access Bluetooth features in android applications.

Output of Android Bluetooth List Paired Devices Example

When we run the above program in the android studio we will get the result as shown below.

Android Bluetooth List Paired Devices Example Result

When we click on Get Paired Devices button, we will get list of paired Bluetooth devices in our android application.

This is how we can get Bluetooth paired devices list in android applications based on our requirements.

Источник

Programmatically connect to paired Bluetooth device

Is there a way, using the Android SDK, to programmatically connect to an already-paired Bluetooth device? In other words: I can go into Settings -> Wireless & networks -> Bluetooth settings, and tap the device (listed as «Paired but not connected»), at which point it will connect. I’d like to be able to do this programmatically, but don’t see a way to do this. I see the options to create an RFCOMM socket, and for a SPP device, I’m assuming that’ll do the connection part as well, but for an A2DP device, where the actual data transfer will be handled by the OS rather than by my app, I think that’s not applicable?

4 Answers 4

Okay, since this was driving me crazy, I did some digging into the source code and I’ve found a 100% reliable (at least on my Nexus 4, Android 4.3) solution to connect to a paired A2DP device (such as a headset or Bluetooth audio device). I’ve published a fully working sample project (easily built with Android Studio) that you can find here on Github.

Essentially, what you need to do is:

  • Get an instance of the BluetoothAdapter
  • Using this instance, get a profile proxy for A2DP:

adapter.getProfileProxy (context, listener, BluetoothProfile.A2DP);

where listener is a ServiceListener that will receive a BluetoothProfile in its onServiceConnected() callback (which can be cast to a BluetoothA2dp instance)

Method connect = BluetoothA2dp.class.getDeclaredMethod(«connect», BluetoothDevice.class);

String deviceName = "My_Device_Name"; BluetoothDevice result = null; Set devices = adapter.getBondedDevices(); if (devices != null) < for (BluetoothDevice device : devices) < if (deviceName.equals(device.getName())) < result = device; break; >> > 

Which, at least for me, caused an immediate connection of the device.

Источник

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