Pairing android bluetooth devices

Android + Pair devices via bluetooth programmatically

I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair. I want to know mistake in my code or any other way to do what i need.

package com.marakana; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class BluetoothDemo extends Activity < // Debugging private static final String TAG = "DeviceListActivity"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; private ArrayAdapter mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() < public void onClick(View v) < doDiscovery(); v.setVisibility(View.GONE); >>); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) < mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> else < String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); >> @Override protected void onDestroy() < super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) < mBtAdapter.cancelDiscovery(); >// Unregister broadcast listeners this.unregisterReceiver(mReceiver); > /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() < if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) < mBtAdapter.cancelDiscovery(); >// Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); > // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewav, View v, int arg2, long arg3) < // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); >>; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); >> > >; > 

Источник

Читайте также:  Хонда фит шаттл магнитола блютуз

Android + Pair devices via bluetooth programmatically

I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair. I want to know mistake in my code or any other way to do what i need.

package com.marakana; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class BluetoothDemo extends Activity < // Debugging private static final String TAG = "DeviceListActivity"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; private ArrayAdapter mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() < public void onClick(View v) < doDiscovery(); v.setVisibility(View.GONE); >>); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) < mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> else < String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); >> @Override protected void onDestroy() < super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) < mBtAdapter.cancelDiscovery(); >// Unregister broadcast listeners this.unregisterReceiver(mReceiver); > /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() < if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) < mBtAdapter.cancelDiscovery(); >// Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); > // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewav, View v, int arg2, long arg3) < // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); >>; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); >> > >; > 

Источник

Читайте также:  Наушники беспроводные bluetooth sony wh ch500

How to pair Bluetooth device programmatically Android

I am developing an application where I want to connect a Bluetooth device main issue is I don’t want user to enter required pin instead application should do that by himself. I don’t have any connection related issue. Only want to insert and complete pin authentication process by application itself. I found following code I am sure it is working but not sure on how to add pin in this code??

private void pairDevice(BluetoothDevice device) < try < Log.d("pairDevice()", "Start Pairing. "); Method m = device.getClass().getMethod("createBond", (Class[]) null); m.invoke(device, (Object[]) null); Log.d("pairDevice()", "Pairing finished."); >catch (Exception e) < Log.e("pairDevice()", e.getMessage()); >> 

8 Answers 8

This seems to give you the answer, with the pin entering and all. It involves sending .setPin() whenever you get the message.

So, I had this question, if someone needs the answer to this working in android 4.4.2.

 IntentFilter filter = new IntentFilter( "android.bluetooth.device.action.PAIRING_REQUEST"); /* * Registering a new BTBroadcast receiver from the Main Activity context * with pairing request event */ registerReceiver( new PairingRequest(), filter); 

And the code for the Receiver.

 public static class PairingRequest extends BroadcastReceiver < public PairingRequest() < super(); >@Override public void onReceive(Context context, Intent intent) < if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) < try < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int pin=intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY", 0); //the pin in case you need to accept for an specific pin Log.d("PIN", " " + intent.getIntExtra("android.bluetooth.device.extra.PAIRING_KEY",0)); //maybe you look for a name or address Log.d("Bonded", device.getName()); byte[] pinBytes; pinBytes = (""+pin).getBytes("UTF-8"); device.setPin(pinBytes); //setPairing confirmation if neeeded device.setPairingConfirmation(true); >catch (Exception e) < e.printStackTrace(); >> > > 

And the broadcastReceiver.

No, I dont think so this solution was for android 4.4.2 and android 5, not sure about android 6 and up. @TejasPandya

Does this solution work without Bluetooth_Priveldge permission? Doesn’t this device.setPairingConfirmation(true); line need the permisiion mentioned above to work ?

@Harrish it should work, but it will depend on the device, some devices require pairing confirmation sent, and some assume that once you are connected you are paired, also this solution was for android 4.4.2 and android 5, so you should probably do something similar for android 6 and above.

The method setPairingConfirmation needs the BLUETOOTH_PRIVILEDGED permission which is not available to third party apps. But with abortBroadcast it’s working on my Pixel 4 XL!

How to set the pin code has been answered above (and that helped me). Yet, I share my simple code below which works with Android 6:

BluetoothAdapter mBTA = BluetoothAdapter.getDefaultAdapter(); if (mBTA.isDiscovering()) mBTA.cancelDiscovery(); mBTA.startDiscovery(); . /** In a broadcast receiver: */ if (BluetoothDevice.ACTION_FOUND.equals(action)) < // One device found. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d(TAG, "Start Pairing. with: " + device.getName()); device.createBond(); >// If you want to auto-input the pin#: else if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action))
public void pairDevice(BluetoothDevice device) < String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST"; Intent intent = new Intent(ACTION_PAIRING_REQUEST); String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE"; intent.putExtra(EXTRA_DEVICE, device); String EXTRA_PAIRING_VARIANT = "android.bluetooth.device.extra.PAIRING_VARIANT"; int PAIRING_VARIANT_PIN = 0; intent.putExtra(EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); >Intent intent = new Intent(BluetoothDevice.ACTION_PAIRING_REQUEST); intent.putExtra(EXTRA_DEVICE, device); int PAIRING_VARIANT_PIN = 272; intent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PIN); sendBroadcast(intent); Intent intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS); startActivityForResult(intent, REQUEST_PAIR_DEVICE); 

Please help me. I want list of device that has BT enabled and after click on particular bluetooth device, it is paired with our device

Register a BluetoothDevice.ACTION_PAIRING_REQUEST receiver onCreate()

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST) registerReceiver(pairingReceiver, pairingRequestFilter) 

on receiver set your pin using setPin() and call abortBroadcast()

val PAIRING_PIN=1234 private var pairingReceiver = object : BroadcastReceiver() < override fun onReceive(context: Context?, intent: Intent?) < val action = intent. action if (BluetoothDevice.ACTION_PAIRING_REQUEST == action) < val device: BluetoothDevice? =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) val type =intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR) if (type == BluetoothDevice.PAIRING_VARIANT_PIN) < device?.setPin(PAIRING_PIN.toByteArray()) abortBroadcast() >> > > 

Don’t forget to unregister receiver on onDestroy()

Читайте также:  Музыкальные центры подключение bluetooth

if it doesn’t work for you, try setting hight priority to receiver

val pairingRequestFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST) pairingRequestFilter.priority = IntentFilter.SYSTEM_HIGH_PRIORITY - 1 registerReceiver(pairingReceiver, pairingRequestFilter) 

Also you can register a receiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED to read status of pairing

val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED) registerReceiver(receiver, filter) 

Источник

Pairing Bluetooth mobile devices in 3 steps

bluetooth_in_mobiles

Nowadays this wireless technology is a common standard that allows us to connect different types of units without any cables or cords. What is Bluetooth used for? It may be used to join a mobile to a car, to join headset to our phone, to use wireless keyboard and mouse with tablet or phone, to act our phone as a modem, to connect mobile to mobile, etc. The average working distance for this technology is not more than about 10 meters so we shouldn’t move connected ones too far from each other.

Today the mobiles are very popular. The total count of them is more that people in the world. So we should know how to connect Bluetooth to the phone to stay modern.

The second device type is varied. One of the most popular wireless gadgets for mobile is a headset. Here is a manual on how to connect the Bluetooth headset unit in 4 steps. Another popular option is pairing a phone with car.

The generic main steps are

We don’t need to connect the units again in further. They automatically connect when they are in the range of each other with wireless mode turned on. Note that using modern technology can increase the level of battery utilization, so we should check the charge level on both units regularly.

Turn off the wireless mode just in case of stop usage. Remove each one from a paired list of other one to completely unpair Bluetooth devices if needed.

The most mobiles released after 2007 have this technology onboard. We may always check it through finding an appropriate setting on the one. Below are detailed pairing instructions for different types such as

How to connect Bluetooth on iPhone and iPad#

Ensure that wireless mode is on, do the same on the second unit and tap on its name in the list of available equipment. The user interface is quite the same for iPad by thanks to Apple.

ios_bluetooth_devices_list

Check Bluetooth passkey (or enter it if necessary) and choose “Pair” to accept the connection.

ios_bluetooth_passkey_validation

Now the mobile and the other unit are paired.

Open it details via information icon and choose “Forget this Device” to unpair the device if necessary.

ios_bluetooth_disconnect_device

Attach Bluetooth on Android phone and tablet#

Ensure that wireless technology is on in “Settings\Bluetooth” and tap on the particular available device that must be wirelessly activated too. Repeat search by “Search for devices” or similar if we can’t find a particular unit in the list.

android_bluetooth_devices_list

Check passkey for Bluetooth (or enter it if necessary) and confirm the connection.

android_bluetooth_passkey_validation

Open it details via configuration icon and choose “Unpair” to disconnect the unit. Also, we can set own local name of paired one via “Rename”.

android_bluetooth_disconnect_device

How to connect Bluetooth on Windows Phone#

Make sure that the mode is on (look at the below picture) and get the list of available ones. The second one should be enabled too. Then find and tap on the second unit name.

windows_phone_bluetooth_devices_list

windows_phone_bluetooth_passkey_validation

Now the mobile and the other unit are paired.

Tap on device in the list and confirm deletion to unpair it in case of no need.

Источник

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