I am trying to discover all available bluetooth devices and pass to another activity.
However even when looking at the Android Docs, I am unable to figure out why I cannot discover any devices and my ArrayList remains empty.
OnClick execute this:
mBluetoothAdapter.startDiscovery();
My broadcast listener also works but nothing is every returned and ArrayList remains empty.
private final BroadcastReceiver mReceiver = 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);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Enabled");
showEnabled();
}
}
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<>();
mProgressDlg.show();
}
if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainScreen.this, DeviceListActivity.class);
if (mDeviceList.isEmpty()){
Log.d("onReceive: ", "EMPTY");
}
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
}
}
};
GIST
Answered my own question.
The fix was to turn location on with app permissions.
Apparently this is required for Android Marshmallow
Related
I'm trying to handle the event when a user presses "ok" or "cancel" on the automatic permission dialog presented when I connect a "known" USB device to the android phone.
I'm using the android.usb.host library and can send and receive between the android phone and the device. Futhermore do I handle the "USB_DEVICE_ATTACHED" and "USB_DEVICE_DETACHED" using a BroadcastReceiver without any problems.
I want to enable a sort of "autoconnect" feature and therefore I need to know when the user has pressed "ok" in the automatically displayed permission dialog, but I can't find anything online at all. All I find is "bypass dialog", but this is not what I want or need.
When I connect the usb device to the android phone, a permission dialog is automatically displayed because I use the "device_filter.xml" solution from androids documentation which can be seen here Android Usb Docs.
This is how I handle the USB_DEVICE_ATTATCHED and USB_DEVICE_DETACHED events:
public NativeUsbService(ReactApplicationContext reactContext) {
...
// register device attached/detached event listeners
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
reactContext.registerReceiver(usbReceiver, filter);
...
}
And then the Broadcast Receiver:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
} else {
Log.d(TAG, "onReceive: DEVICE WAS ATTACHED AND WAS NULL :(");
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "onReceive: Device was detached!");
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
}
}
};
I have tried multiple different approaches, but nothing has worked.
I have tried getting the user response in from the intent, like with a manual permission request like below:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
// THIS DOES NOT WORK ↓↓↓
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
// The code never gets here...
}
} else {
Log.d(TAG, "onReceive: DEVICE WAS ATTACHED AND WAS NULL :(");
sendEvent("onDeviceAttached", false);
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
}
}
};
I have also tried by adding a usb permission listener to the broadcast receiver by first adding the action name to my class variables:
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
Then adding the action to my intent filter like so:
public NativeUsbService(ReactApplicationContext reactContext) {
// register device attached/detached event listeners
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_PERMISSION); // added action to my intent filter
reactContext.registerReceiver(usbReceiver, filter);
}
And finally reacting to the action like so:
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device != null){
usbDevice = device;
}
}
} else if (action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "onReceive: Device was detached!");
if(connection != null) {
connection.releaseInterface(usbDeviceInterface);
connection.close();
}
connection = null;
usbDevice = null;
endpointIn = null;
endpointOut = null;
sendEvent("onDeviceDetached", true);
}
else if (action.equals(ACTION_USB_PERMISSION)) {
Log.d(TAG, "onReceive: ACTION_USB_PERMISSION");
if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
Log.d(TAG, "onReceive: EXTRA_PERMISSION_GRANTED = true");
} else Log.d(TAG, "onReceive: EXTRA_PERMISSION_GRANTED = false");
}
}
};
Please make me aware of any missing information.
Any help is greatly appreciated.
Answering my own question in case someone else is facing the same issue.
I though about manually requesting the permission again, after permission was granted, since it is possible to handle this manual permission request when user presses an option in the dialog. I discarded this idea, not because it wouldn't work, but because I saw it as unecessary for the user to also have to press another dialog after the initial (automatic dialog).
I must add that I have not implemented this solution, so I do not know with certainty that it would prompt the user again, but I have had trouble with the manual permission request previously. If you want to try this approach the method belongs to the UsbManager class and is invoke like so usbManger.requestPermission(usbDevice).
I ended up with a solution where I start a thread which runs a loop calling usbManager.hasPermission(usbDevice) until it has permission and then emits an event (emitting this event is my use case, implement it how you like).
The solution can be seen here:
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import com.facebook.react.bridge.ReactApplicationContext;
...
private static volatile boolean permissionThreadShouldStop = false;
private static Thread activePermissionThread = null;
...
public static void usbPermissionEventEmitter(ReactApplicationContext reactContext, UsbManager usbManager, UsbDevice usbDevice) {
if((activePermissionThread != null && activePermissionThread.isAlive())) {
activePermissionThread.interrupt();
}
permissionThreadShouldStop = false;
activePermissionThread = new Thread(new Runnable() {
#Override
public void run() {
while (!usbManager.hasPermission(usbDevice) && !permissionThreadShouldStop) {
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
if(usbManager.hasPermission(usbDevice)) {
sendEvent(reactContext, "onUsbPermissionGranted", true);
}
}
});
activePermissionThread.start();
}
The ReactApplicationContext can be swapped with the normal android context. But this is for a react native module, so I use the reactContext.
I hope this will be helpful for someone, because i'm honestly really surpriced how scarse the android documentation is in regards to implementing Usb functionality using the android.hardware.usb library.
Also in general when searching for information online, I have often found myself lost since there is very little information on this subject.
Currently I developed a new method to discover bluetooh ready connections. Here is my code:
private void DiscoverOBDConnection() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver;
// Create a BroadcastReceiver for ACTION_FOUND
final List<String> discoverableDevicesList = new ArrayList<String>();
mReceiver = new BroadcastReceiver() {
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);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
discoverableDevicesList.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
String discoveredDeviceName = device.getName();
discoverableDevicesList.add(discoveredDeviceName);
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
context.registerReceiver(mReceiver,filter); // Don't forget to unregister during onDestroy
}
I just do not know how to call the onreceive method from another method. Could you help me to learn how to implement and discover the ready to connect bluetooth devices?
You can just send broadcast
Intent i = new Intent(BluetoothDevice.ACTION_FOUND);
sendBroadcast(i);
Or call it directly
mReceiver.onReceive(this, new Intent(BluetoothDevice.ACTION_FOUND));
I've seen some apps on the playstore that can read the RSSI of all devices in range via Bluetooth, how is that possible? I'm currently running a code that can get me one and only one RSSI (which is the nearest one available).
Any possible way to get the RSSI of a specific device? Or even better, get the RSSI of all the devices in range?
I'm using the EXTRA_RSSI code at the moment, but I need to get the RSSI of the whole list or a specific device.
Here's the method I'm using (it's working fine, but again, only the nearest is getting capted)
private final BroadcastReceiver receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
//BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//for (BluetoothDevice dv : pairedDevices) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)) {
int rssit = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
int rssi = Math.abs(rssit); // Just for visual analysis
String name = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
if (!l_name.contains(name)) {
RadioButton Rb = new RadioButton(getBaseContext());
Rb.setId(l_name.size());
Rb.setText(name);
Rb.setTypeface(Typeface.DEFAULT_BOLD, R.style.TextAppearance_AppCompat_Widget_DropDownItem);
Rb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s_name = ((RadioButton) view).getText().toString();
}
});
l_name.add(name);
((RadioGroup) findViewById(R.id.radiogroup)).addView(Rb);
}
//if (s_name != name) return;
String RSSI = "";
((TextView) findViewById(R.id.textView)).setText(name);
((TextView) findViewById(R.id.range)).setText(RSSI + " " + rssit);
}
//}
}
};
Your onReceive() callback should be getting called for every nearby advertising device. If you do BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); then you should see that you're actually getting different device instances for each call to onReceive(). Eventually they will start to repeat, but if there are 3 advertising devices nearby you should get at least 3 callbacks. Log BluetoothDevice#getAddress() to confirm the behavior.
I have a mUsbReceiver (BroadcastReceiver) and CameraActivity. The receiver setContentView(R.layout.main) from CameraActivity via an Intent. Then CamearActivity updates its View with this value. Notice that the setContentView is in the Broadcast receiver class and not in the CameraActivity Class.
public class CameraActivity extends Activity {
private static final String TAG = "openXC::Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
usbConnection();
}
public void usbConnection() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_CANCEL_CURRENT);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
String txt = "default";
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Log.i(TAG, "Device List: " + deviceList);
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next();
Log.i(TAG, "Device List: " + deviceList);
mUsbManager.requestPermission(device, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION ="com.ford.openxc.webcam.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){
Log.d(TAG, "Displayed Comten View " + device);
setContentView(R.layout.main);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
}
This works fine sometimes but sometimes throws the following error
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/Adreno200-EGLSUB( 5609): <ConfigWindowMatch:2087>: Format RGBA_8888.
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
D/openXC::Activity( 5609): Displayed Comten View UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421d3ed0]
D/WebcamPreview( 5609): WebcamPreview constructed
Technically, you can call setContentView any time you are executing on the event thread.
Otherwise you need to use a Handler to call it.
Also, here are some usefull links that might help you:
link1
link 2
link 3
I dont have much exp on USB sort of thing but since u said its saying cannot readfile.. i believe dat the error may be in the usb so for the debugging purpose i would suggest to move the setContentView(int) from if conditions to the onRecieve directly so dat whenever the onReceive is called ur contenview will change , this will help to ensure that the error is not with setcontentview... After dat u can see without setcontentview in the usb and now if the error is coming then surely the error is in the usb and not in the setContentView ....
Hope it works :)
how is it possible to get the Bluetooth information (name, Mac address,...) of the peer device that the android device is connected to that via Bluetooth ?
You can use the following code to get all remote devices :)
private void discoveryDevice(){
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
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();
// 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);
Log.d(TAG, "device " + device.getName() + "\n" + device.getAddress());
}
}
};
It's really good for you to get the name of remote device throught the code:
Log.d(TAG, "device " + device.getName() + "\n" + device.getAddress());
I can't test this code at this moment but maybe can give an idea to how you can get the name and others parameters of bluetooth.
static BluetoothSocket socket ;
public static boolean btCon(Context ctx){
Method m;
try {
BluetoothDevice devc = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(MAC_ADRS);
m = devc.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
socket = (BluetoothSocket)m.invoke(devc, Integer.valueOf(1));
socket.connect();
String name = devc.getName();/* or */ String name2 = devc.getName().toString();
Log.i("Test","Name: "+name);
Log.i("Test","Name 2: "+name2);
return true;
}catch(Exception e)
{
return false;
}
}