How to scan for available bluetooth devices in range in android? - android

I need to get a list of available bluetooth devices in the area using google android 2.1.
Thing is, i don't just need a list of those devices, i need some unique id for each device found and i need an indicator, how "good" the signal is received (like the "level" in android.wifi.ScanResult)... How do i do that?

Check out code below :
Starting search
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);

Call method bluetoothScanning, context is required
void bluetoothScanning(){
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver, filter);
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Log.i("Device Name: " , "device " + deviceName);
Log.i("deviceHardwareAddress " , "hard" + deviceHardwareAddress);
}
}
};
Result
Name: LE-Bose Revolve+ SoundLink
deviceHardwareAddress: MAC .....

This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.
Make sure you import BeaconManager
private BeaconManager beaconManager;
//In onCreate method
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser().
setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
//use these out of the onCreate method
public void onScanStart(View view) {
stopScanButton.setEnabled(true);
scanningButton.setEnabled(false);
beaconManager.bind(this);
}
#Override
public void onBeaconServiceConnect() {
beaconManager.removeAllRangeNotifiers();
beaconManager.addRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for (Beacon b : beacons) {
System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi()));
});
try {
//Tells the BeaconService to start looking for beacons that match the passed.
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
} catch (RemoteException e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
Let me know if that works for you!

To able to discovery devices by bluetooth. Make sure you
Enable bluetooth
Allow required permissions for your application (some permission is runtime permission). You can check here https://developer.android.com/about/versions/12/features/bluetooth-permissions
AndroidManifest.xml
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
MainActivity
class MainActivity : AppCompatActivity() {
private var bluetoothAdapter: BluetoothAdapter? = null
private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent) {
val action = intent.action
Log.i("TAG", "onReceive $action")
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
Log.i("TAG", "Discovery finished, hide loading")
} else if (BluetoothDevice.ACTION_FOUND == action) {
val device =
intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
Log.i("TAG", "Device Name: " + (device?.name ?: ""))
Log.i("TAG", "Device Address:" + (device?.address ?: ""))
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
...
findViewById<Button>(R.id.button_start_discovery).setOnClickListener {
if (bluetoothAdapter == null) {
initBluetoothDiscovery()
}
startDiscovery()
}
}
private fun initBluetoothDiscovery() {
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
val intentFilter = IntentFilter().apply {
addAction(BluetoothDevice.ACTION_FOUND)
addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
}
registerReceiver(bluetoothReceiver, intentFilter)
}
private fun startDiscovery() {
if (bluetoothAdapter?.isDiscovering == true) {
Log.i("TAG", "cancel start discovery")
bluetoothAdapter?.cancelDiscovery()
}
Log.i("TAG", "start discovery, show loading")
bluetoothAdapter?.startDiscovery()
}
override fun onDestroy() {
super.onDestroy()
bluetoothAdapter?.cancelDiscovery();
unregisterReceiver(bluetoothReceiver);
}
}

Related

android: Bluetooth won't discover devices

I'm writing an Android-App, which is supposed to discover devices via Bluetooth.
I don't get any exceptions, but the devices are just not found, even though my windows pc finds them (and can be found itself).
I'm certain they are BLE, but I tried both ways. And of course I tried them separately.
Here is my ListActivity, which searches for the devices:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.bluetooth_list_view);
listView = getListView();
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, "BLE is not supported", Toast.LENGTH_SHORT).show();
finish();
}
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
Log.d(TAG, "on Create start5");
if (mBluetoothAdapter == null) {
Toast.makeText(this, "BLE is not supported", Toast.LENGTH_SHORT).show();
finish();
return;
}
mLeDeviceListAdapter = new LeDeviceListAdapter(this);
setListAdapter(mLeDeviceListAdapter);
listView.setAdapter(mLeDeviceListAdapter);
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
private void scanLeDevice(final boolean enable) {
Log.e(TAG, "scanLeDevice: " + enable);
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.e(TAG, "after Scan mLeDeviceListAdapter: " + mLeDeviceListAdapter.getCount());
Log.e(TAG, "after Scan isEmpty(): " + mLeDeviceListAdapter.isEmpty());
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothLeScanner.startScan(mScanCallback);
} else {
mScanning = false;
mBluetoothLeScanner.stopScan(mScanCallback);
}
invalidateOptionsMenu();
}
The logs say after Scan mLeDeviceListAdapter: 0 and after Scan isEmpty(): true.
ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.e(TAG, "onScanResult: " + result);
super.onScanResult(callbackType, result);
mLeDeviceListAdapter.addDevice(result.getDevice());
mLeDeviceListAdapter.notifyDataSetChanged();
}
};
That log (onScanResult) is never called.
And for not BLE:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() { //TODO not ble example
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e(TAG, "Not BLE discovry starts");
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e(TAG, "Not BLE discovry finishes");
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "Found device " + device.getName());
}
}
};
Not BLE discovry finishes is printed and so is Not BLE discovry starts. Found device is never printed. But I'm positiv that the devices are BLE.
I have the necessary permissions in my manifest:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
What am I doing wrong?
Edit:
i really need help. Thinks I tried/checked so far:
Enabled Bluetooth adapter.
Bluetooth usage permissions granted.
Location permission (ACCESS_COARSE and ACCESS_FINE) granted.
Made sure gps provider is enabled (Smartphone GPS settings).
Maybe because you didn't request ACCESS_COARSE_LOCATION in onCreate
This project is a good resource for you to start your Bluetooth scanner:
https://github.com/joelwass/Android-BLE-Scan-Example

Android Kernel OTG

How can I use an app to detect when the otg cable is plugged in and when it's not?
Is there an intent for otg cables like the one below for usb devices: "android.hardware.usb.action.USB_DEVICE_ATTACHED"
I have created an app but it only detects a flash drive and not an otg cable:
public class MainActivity extends AppCompatActivity
{
private TextView mInfo;
private Logger mLogger;
private HashMap<UsbDevice, UsbDataBinder> mHashMap = new HashMap<UsbDevice, UsbDataBinder>();
private UsbManager mUsbManager;
private PendingIntent mPermissionIntent;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInfo = (TextView)findViewById(R.id.log);
mLogger = new Logger(this);
mLogger.setMode(Logger.MODE_TOAST);
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
usbConnection();
}
private void usbConnection() {
IntentFilter filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbAttachReceiver , filter);
filter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(mUsbDetachReceiver , filter);
mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
showDevices();
}
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mUsbDetachReceiver);
unregisterReceiver(mUsbAttachReceiver);
unregisterReceiver(mUsbReceiver);
};
BroadcastReceiver mUsbDetachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (device != null) {
// call your method that cleans up and closes communication with the device
UsbDataBinder binder = mHashMap.get(device);
if (binder != null) {
binder.onDestroy();
mHashMap.remove(device);
Toast.makeText(MainActivity.this, "Attached!", Toast.LENGTH_SHORT).show();
}
}
}
}
};
BroadcastReceiver mUsbAttachReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
showDevices();
Toast.makeText(MainActivity.this, "Detached!", Toast.LENGTH_SHORT).show();
}
}
};
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// call method to set up device communication
UsbDataBinder binder = new UsbDataBinder(mUsbManager, device);
mHashMap.put(device, binder);
Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
}
} else {
// Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
private void showDevices() {
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while(deviceIterator.hasNext()){
UsbDevice device = deviceIterator.next();
mUsbManager.requestPermission(device, mPermissionIntent);
//your code
mLogger.log("usb", "name: " + device.getDeviceName() + ", " +
"ID: " + device.getDeviceId());
mInfo.append(device.getDeviceName() + "\n");
mInfo.append(device.getDeviceId() + "\n");
mInfo.append(device.getDeviceProtocol() + "\n");
mInfo.append(device.getProductId() + "\n");
mInfo.append(device.getVendorId() + "\n");
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
I never tried USB OTG, but from https://github.com/shakalaca/USB-OTG-Manager you can use
<intent-filter>
<action android:name="com.sonyericsson.hardware.action.USB_OTG_DEVICE_CONNECTED" />
<action android:name="com.sonyericsson.hardware.action.USB_OTG_DEVICE_DISCONNECTED" />
<action android:name="com.sonyericsson.hardware.action.USB_OTG_ERROR" />
<action android:name="com.sonyericsson.usbotg.ACTION_ERROR_OK" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
From the documentation:
USB OTG Manager
This software is originally designed for Sony Ericsson Xperia Arc S.
Since OTG is enabled in kernel, I'm wondering why I can't access my
memory stick. So I've created this little application for reading
books on my thumb disk, and happily ever after ! :D
Supported Phone:
* Sony Ericsson Xperia Arc S (4.0.2.A.042, 4.0.2.A.062)
* Sony Ericsson Xperia Mini Pro (4.0.2.A.042, 4.0.2.A.058)
* Samsung Galaxy Nexus
Supported USB Device:
* FAT USB memory stick
* Card Reader
related project: https://github.com/mik3y/usb-serial-for-android
you're on your own boat now.

How to dismiss bluetooth pairing request dialog completely?

My app should pair with a BLE without showing any pairing request dialog. I am setting pin in the code. But actually dialog is showing for a sec and then disappearing. Pairing is happening, but i don't want this dialog to be shown. Is there a method to do that?
Since the SDK version 19 this is more difficult. I found a way to bypass it using a subclass of BroadcastReceiver.
public class BluetoothPairingRequest extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
// convert broadcast intent into activity intent (same action string)
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int type = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.ERROR);
Intent pairingIntent = new Intent();
pairingIntent.setClass(context, MainActivity.class);
pairingIntent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, type);
pairingIntent.setAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
pairingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (device != null) {
try {
device.setPin("1111".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
context.startActivity(pairingIntent);
}
}
}
Then you need register a bond receiver like this.
/**
* Lock used in synchronization purposes
*/
private final Object lock = new Object();
private String deviceAddress;
...
#Override
public void onCreate() {
super.onCreate();
...
final IntentFilter bondFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(bondStateBroadcastReceiver, bondFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
...
unregisterReceiver(bondStateBroadcastReceiver);
}
After this you can add this code when you want to initialize the bonding process.
...
BluetoothDevice newDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());
deviceAddress = newDevice.getAddress();
createBond(newDevice);
...
The implementation of the createBond is here:
private final BroadcastReceiver bondStateBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
// Obtain the device and check it this is the one that we are connected to
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!device.getAddress().equals(mDeviceAddress))
return;
// Read bond state
final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
if (bondState == BluetoothDevice.BOND_BONDING)
return;
requestCompleted = true;
// Notify waiting thread
synchronized (lock) {
lock.notifyAll();
}
}
};
private boolean createBond(final BluetoothDevice device) {
if (device.getBondState() == BluetoothDevice.BOND_BONDED)
return true;
boolean result;
requestCompleted = false;
sendLogBroadcast(LOG_LEVEL_VERBOSE, "Starting pairing...");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
result = device.createBond();
} else {
result = createBondApi18(device);
}
// We have to wait until device is bounded
try {
synchronized (lock) {
while (!requestCompleted) lock.wait();
}
} catch (final InterruptedException e) {
Log.e(TAG, "Sleeping interrupted", e);
}
return result;
}
private boolean createBondApi18(final BluetoothDevice device) {
/*
* There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19)
*/
try {
final Method createBond = device.getClass().getMethod("createBond");
if (createBond != null) {
return (Boolean) createBond.invoke(device);
}
} catch (final Exception e) {
Log.w(TAG, "An exception occurred while creating bond", e);
Log.e(TAG, e.toString());
}
return false;
}
Finally don't forget to add to your manifest these lines:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And register the receiver:
<receiver android:name=".bluetooth.BluetoothPairingRequest">
<intent-filter>
<action android:name="android.bluetooth.device.action.PAIRING_REQUEST" />
<action android:name="android.bluetooth.device.action.PAIRING_CANCEL" />
</intent-filter>
</receiver>

Can`t run BlueTooth discovery from Service

I can`t run startDiscovery (for BlueTooth) from Service.
Service run from sleep by WakefulBroadcastReceiver (by timer).
Source code of Service:
public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = "LocationService";
private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service onCreate");
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mBTReceiver, filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service onStartCommand");
BTscanner();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(mBTReceiver);
}
private void BTscanner() {
Log.e(TAG, "==BT: Run BTscanner");
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
Log.e(TAG, "==BT: End BTscanner");
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e(TAG, "==BT: Started");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.e(TAG, "==BT: Finished");
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e(TAG, "==BT: " + device.getAddress());
}
}
};
}
In log i see:
Service onStartCommand
==BT: Run BTscanner
==BT: End BTscanner
but don`t see:
==BT: Started
==BT: Finished
and list of discovered devices.
In Manifest all permissions installed:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
and service enabled in application field of Manifest:
<service
android:name=".LocationService"
android:enabled="true"
android:exported="true" />
What did I do wrong?
Tnx.
Are you sure that your receiver has not been unregistered in the onDestroy method before having the time to handle any action? I would put a break point in it to see what's happenning in there?
I think, I found a solution.
There were problems when I install and run the application with active Bluetooth on smartphone.
After installing application and manual deactivate/activate Bluetooth device all works fine.
Maybe it was some sort of a hardware failure.
Then reinstall the application twice, and the problem is not repeated.

Android want to send bluetooth pair request to another devices

i want to search and listing bluetooth devices in android, my program now able to list all the active devices but not able to send pairing request to the other devices .I want to implement this onItemClick of list element.And also if bluetooth is not enabled of my device then show a permission to active device,if i go for yes then ok,but if i go for no then permission show again until i press yes..how can i do this?plz help with code..here is my code..
public class Main extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
private ArrayList<String> mylist= new ArrayList<String>();
private ListView lv;
private Button btn;
public Parcelable[] uuidExtra;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view)
{
//Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();
CheckBTState();
}
private void setDeviceList(ArrayList<String> list) {
lv = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
/* This routine is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBTState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// If it isn't request to turn it on
// List paired devices
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
return;
} else {
if (btAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();
// Starting the device discovery
btAdapter.startDiscovery();
} else if (!btAdapter.isEnabled()){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/* else{
Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
startActivityForResult(intent, RESULT_CANCELED);
}*/
}
}
private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device,5000).show();
mylist.add(device.getName());
setDeviceList(mylist);
} else {
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (int i=0; i<uuidExtra.length; i++) {
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
}
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
if(!device.fetchUuidsWithSdp()) {
Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
}
}
}
}
}
}
}
};
}
It's too late but here is code -> You need to use background thread to connect with bluetooth device as a client. and UUID is Universal Uniquely identification you can use online UUID generator. for secure connections and then get socket with device and connect with it;
ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}

Categories

Resources