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.
Related
I am trying to discover bluetooth devices and append results to TableLayout.
Basically, I'm trying to start the discovery and print deviceName and rssi to table layout.
Here is my code:
public class DatabaseActivity extends AppCompatActivity {
public BluetoothAdapter bluetoothAdapter;
private final BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
// Append to tableBLE
TableLayout tl = findViewById(R.id.tableBLE);
appendTableFront(tl, deviceName + "_" + rssi);
Log.d("PBK_Test - Detected", deviceName + "_" + rssi);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
// Bluetooth
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
}
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
}
// Start Discovery
bluetoothAdapter.startDiscovery();
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
// Make discoverable
if (bluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public void appendTableFront(TableLayout tl, String msg) {
TableRow newRow = new TableRow(this);
newRow.setBackgroundColor(Color.GRAY);
newRow.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
TextView label_id = new TextView(this);
label_id.setText(msg);
label_id.setTextColor(Color.WHITE);
label_id.setPadding(5, 5, 5, 5);
newRow.addView(label_id);
tl.addView(newRow);
}
}
I can become discoverable, but not detecting other devices.
I tried the built-in bluetooth discovery and it works fine.
Edit:
I added Log.d("PBK_Test - Detected", deviceName + "_" + rssi); to onReceive and it is not shown as well.
newRow might be null, because there's no final keyword and you change the scope.
Remove this instruction: runOnUiThread() ...because it's not running in the background.
I figured it out myself.
The problem is not in the code --
You have to get into Settings -> App -> <app_name> -> Permissions, to manually give your app permissions, EVEN IF YOU HAVE DECLARED THEM IN MANIFEST.
Citation:
This video https://www.youtube.com/watch?v=dLZDJgblgj8
I want to implement passkey for connect device or establish the connection with BLE device. I have 6 byte passkey, So how we will create bond or pairing and send passkey to the BLE device using RxAndroid library.
Can any one give me reference or document link or demo link for implementation of Passkey or create bond or pairing while establish connection.
Thanks in advance!!
First you need to find the nearby devices.
public void registerDeviceForAnyNEwDeviceFound() {
// Register for broadcasts when a device is discovered.
mBluetoothAdapter.startDiscovery();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mSearchReceiver, filter);
Log.e("STATUS", "" +
mBluetoothAdapter.isDiscovering());
isSearchReceiverRegistered = true;
}
// Create a BroadcastReceiver for ACTION_FOUND.
private final BroadcastReceiver mSearchReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("SEARCH STARTED", "TRUE");
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Discovery has found a device. Get the BluetoothDevice
// object and its info from the Intent.
try {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Device mDevice = new Device();
mDevice.setDeviceName(deviceName);
mDevice.setDeviceAddress(deviceHardwareAddress);
mDevice.setmBluetoothDevice(device);
Log.e("Discovered DEVICE", deviceName);
Log.e("BOND STATE", "" + device.getBondState());
nearbyDeviceList.add(mDevice);
mNearbyDeviceRecAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e("EXCEPTION", e.getLocalizedMessage());
}
}
}
};
Then you need to register another BroadCastReceiver, this receiver will listen to the bond changes with the device with whom you are going to pair with.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mPairingReceiver, filter);
private final BroadcastReceiver mPairingReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDED." + mDevice.getName());
mBluetoothAdapter.cancelDiscovery();
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
Log.e(TAG, "BroadcastReceiver: BOND_BONDING." + mDevice.getName());
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
Log.e(TAG, "BroadcastReceiver: BOND_NONE." + mDevice.getName());
}
}
}
};
Finally when you want to pair with the device call:
mNearbyDeviceRecAdapter.getItemAtPosition(position).getmBluetoothDevice().createBond();
Once you call this statement, this will initiate pairing with the device.
Hope! this helps.
I have made an application that allows many-to-one communication using Bluetooth and it is working perfectly fine. Now, i wanted to use the service of the application in another application (e.g. Discovering Devices, Connecting to Device). So, I marked my project as library and added it as library in my new project. However, when i call the Discovering Device Activity (Available in library) from the application, the activity starts, but it doesn't discovers the devices ? Can someone help on this ?
I have included all the library project activity and permissions in my app's manifest.
Here is the sample code for the same -
In Library -
This is how the DeviceListActivity Looks like -
`
public class DeviceListActivity extends Activity{
String insecure="8ce255c0-200a-11e0-ac64-0800200c9a66";
private int flag=0;
int flag_toast=0;
ArrayList<Pair<String,String>> x=new ArrayList<Pair<String,String>>();
private static final String TAG = "DeviceListActivity";
ArrayList<String> temp=new ArrayList<String>();
Map<String, String> services = new HashMap<String, String>();
/**
* Return Intent extra
*/
public static String EXTRA_DEVICE_ADDRESS = "device_address";
/**
* Member fields
*/
private BluetoothAdapter mBtAdapter;
/**
* Newly discovered devices
*/
ImageView animation;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_device_list);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
animation=(ImageView)findViewById(R.id.imageAnimation);
/*scanButton.setOnClickListener(new View.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
//ArrayAdapter<String> pairedDevicesArrayAdapter =new ArrayAdapter<String>(this, R.layout.device_name);
//mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
//Register for broadcasts when a device is discovered
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(mReceiver, filter);
/* 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();
animation.setBackgroundResource(R.drawable.animation);
doDiscovery();
}
#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
*/
public void doDiscovery() {
Log.d(TAG, "doDiscovery()");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
private void connect_automatic(String name){
flag++;
Log.d(name,"Called " + Integer.toString(flag)+" times");
Log.d("Flag is = ",Integer.toString(flag));
int i,j;
for(i=0;i<x.size();i++){
for (j=i+1;j<x.size();j++)
if (x.get(i).getFirst().equals(x.get(j).getFirst())==true && x.get(i).getSecond().equals(x.get(j).getSecond())==true)
x.remove(j);
}
for(i=0;i<x.size();i++){
Log.d("Found "+x.get(i).getFirst(),x.get(i).getSecond());
}
Log.d("Size =",Integer.toString(x.size()));
if (x.size()>=1){
Log.d("Size is =",Integer.toString(x.size()));
String address = x.get(0).getFirst();
if (flag_toast==0)
Toast.makeText(DeviceListActivity.this, "Merchant Found", Toast.LENGTH_SHORT).show();
flag_toast++;
Log.d("Connecting to ",x.get(0).getFirst());
// 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
flag++;
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
//mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btDeviceList.add(device);
// When discovery is finished, change the Activity title
}
else
{
Log.d("Action=",action.toString());
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuidExtra!=null)
for (int i=0; i<uuidExtra.length; i++) {
if(uuidExtra[i].toString().length()>0){
Log.d("\n Device: " + device.getName() + ", " + device, ", Service: " + uuidExtra[i].toString());
// services.put(device.getName(), uuidExtra[i].toString());
//flag=btDeviceList.size();
if (/*uuidExtra[i].toString().equals(secure)==true ||*/ uuidExtra[i].toString().equals(insecure)==true){
Pair<String,String> t=new Pair<String, String>(device.getAddress(), uuidExtra[i].toString());
x.add(t);
}
//connect_automatic();
}
}
Log.d("Device List =",Integer.toString(flag));
connect_automatic(device.getName());
//Log.d("Boolean",Boolean.toString(services.isEmpty()))
}
else
{
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.d("Discovery","Started...");
}
else
{
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d("Discover","Finished");
//setProgressBarIndeterminateVisibility(false);
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
temp.add(device.getName());
Log.d("ok","Getting Services for " + device.getName() + ", " + device);
if(!device.fetchUuidsWithSdp()) {
Log.d("!ok","SDP Failed for " + device.getName());
}
else{
Log.d("SDP Passed for ",device.getName());
}
}
//connect_automatic();
}
}
}
}
}
};}`
And here is how i call it in my new application -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null)
{
ensureDiscoverable();
Intent intent = new Intent(this, DeviceListActivity.class);
startActivityForResult(intent, REQUEST_CONNECT_DEVICE_INSECURE);
}
}
For my application I need to make the android device act as the USB Host. It needs to send and receive data from USB connected devices. I have gone through USB Host in Android Developers Site, and developed sample code as follows:
Main.java
public class UsbDemoProjActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "button click", 30).show();
Intent it = new Intent(UsbDemoProjActivity.this,Second.class);
startActivity(it);
}
});
}
}
Second.java:
public class Second extends Activity{
UsbDevice device;
UsbManager mUsbManager;
PendingIntent mPermissionIntent;
private static String ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("111111111");
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
ACTION_USB_PERMISSION ="com.android.example.USB_PERMISSION";
System.out.println("2222222222");
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
device = deviceList.get("deviceName");
System.out.println("33333333333");
mPermissionIntent = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
System.out.println("444444444444");
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
System.out.println("555555555555");
registerReceiver(mUsbReceiver, filter);
System.out.println("66666666666");
mUsbManager.requestPermission(device, mPermissionIntent);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("7777777777777");
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
System.out.println("88888888888");
UsbDevice device = (UsbDevice)intent.getParcelableExtra(
UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
System.out.println("99999999999999");
//call method to set up device communication
}
} else {
//Log.d(TAG, "permission denied for device " + device);
System.out.println("permission denied for device" + device);
}
}
}
}
};
}
However, when I click on button in Main.java page it is showing an error as:
Unfortunately USBDemoProj has been stopped
and in logcat displaying error as per the below image but here the system.output() lines are displaying which are declared in Second.java class. Can anyone please help me what is the error in my app?
Also, am I using the correct method in my sample code to access devices in USB Host Mode? Can anyone suggest me a better way?
I'm using a slickdev library to talk to my serial device, so I'm not sure about your code. It's not onDataReceived()? That might just be the library's function but...
our manifests should both have this in it:
<uses-feature android:name="android.hardware.usb.host" android:required="true"></uses-feature>
and in the
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="#xml/device_filter" />
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);
}
}