I want to establish a WiFi-Direct Connection with another device peered through NFC. My steps are as follows:
First, Device A gets its own WiFiP2P address and transmits it to Device B via NFC.
Then, Device B tries to establish a connection with Device A using the provided address.
As you can see I didn't involve discovering peers in the process. But when Device B is trying to connect, the result is always failed (reason 0, this should be ERROR).
I think this might be related to device visibility, but I don't know and can't find any code to make a device visible.
Here's my code:
//NOTE: These code should be executed on Device B
//Starting WiFi Direct Transmission
//First we should establish a connection
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = remoteWifiP2pDevice;
//remoteWifiP2pDevice is the address of device A obtained from NFC
config.wps.setup = WpsInfo.PBC;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
//success logic
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
if (!FILE_RECV)
{
new SendFilesTask().execute("");
}
}
#Override
public void onFailure(int reason) {
//failure logic
Toast.makeText(MainActivity.this, "failed" + reason, Toast.LENGTH_SHORT).show();
}
});
In OnCreate() I have
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
The WifiDirectBroadcastReceiver has code only related to getting Device A's address and can be considered empty.
So what's wrong with these and how can I fix it?
Thanks in advance.
P.S. If I connect Device A and B manually, and run my code again, it returns success.
WIfi Direct assumptions:
All the devices should be in discoverable (scanning mode)
simultaneously.
Devices scan for a 30 sec and after that
it stops by default.So we need to initiate scan programatically
using discoverpeers method.
Most important is displaying
nearby devices is device specific.ie sometimes devices wont show
nearby ones eventhough they are available.Thats why wifi direct
is not reliable and because of these, there wont be much wifi
direct apps in play store.
I have discovered that delaying several seconds will make the connection succeed. I don't know the reason, but this can be used as a workaround.
So after all is there a better solution to this? And why does the delay work?
Related
I'm trying to connect to a specific wifi network in android 10. I already have the credentials available to me, and i'm adding the network suggestion:
val suggestion = WifiNetworkSuggestion.Builder()
.setSsid("ssid")
.setWpa2Passphrase("password")
.build()
wifiManager.removeNetworkSuggestions(mutableListOf(suggestion))
when (wifiManager.addNetworkSuggestions(mutableListOf(suggestion))) {
WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS -> {
networkAdded()
}
WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE -> {
networkDuplicate()
}
else -> {
networkAddFailed()
}
}
I'm able to see the notification (though only the first time the app requests this, which makes sense for the most part, since it's asking for permission really to be able to suggest networks). However, after I allow it, i can't seem to get connected to that network. In particular if i already have a wifi connection to some other network.
The new network does not appear in my list of saved networks, and if i find it in the wifi scan list, and click on it, it treats it like a new network.
I don't expect the app to be able to force the system to connect, but i would expect the user to be able to do it on their own via the wifi settings without having to configure it from scratch.
I've also tried using ConnectivityManager to forcibly connect, but that does not add an actual persistent wifi connection. It's only meant to force connection for a specific app while the app is in memory (at least that's my understanding of it).
I had the same issue but after I added this piece of code the device was connected to the network:
final IntentFilter intentFilter = new IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION)) {
return;
} else {
// Do something with success
}
}
};
context.registerReceiver(broadcastReceiver, intentFilter);
Hope that it helps. You can find the complete code example in: Wi-Fi suggestion API
I have written an app that connects to a BLE device. The app works OK on most devices; but some devices (most noticeably Huawei P8 Lite and Nexus 6P) refuse to connect after the Bluetooth adapter has been disabled.
This is the test sequence:
Make sure the app is NOT running.
Slide down from the top, disable BT for a couple of seconds, then re-enable bluetooth.
Start the app. The app automatically connects to a bluetooth address stored in the preferences.
Wait for connect. This is where nothing happens on Huawei phones, but other phones, such as Samsung, works like a charm.
Verify from another phone the device is advertising and you can
connect to it.
This is the code I use to connect:
private final Runnable mBeginConnectRunnable = new Runnable() {
#Override
public void run() {
synchronized (GattConnection.this) {
if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
try {
mBluetoothAdapter.cancelDiscovery();
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mAddress);
mGatt = mBluetoothDevice.connectGatt(mContext, mBackgroundConnect, mGattCallback);
final boolean connectSuccess = mGatt.connect();
Log.d(TAG, String.format(Locale.ENGLISH, "mGatt.connect(%s, %s) %s",
mAddress,
mBackgroundConnect ? "background[slow]" : "foreground[fast]",
connectSuccess ? "success" : "failed"));
refreshDeviceCache(mGatt);
} catch (Exception ex) {
Log.e(TAG, "Create connection failed: " + ex.getMessage());
setState(State.Closed);
}
} else {
Log.d(TAG, "Can't create connection. Adapter is disabled");
setState(State.Closed);
}
}
}
};
All calls are posted via a Handler to the main thread. I can see it waits for a connect, gives up after 30 seconds at which I call BluetoothGatt.close() on the object and nulls it. It's like nothing is out there.
After some time, later in the day, it works again.
Help is highly appreciated :-)
Update September 14, 2018: After great explanation from Emil I've updated our app and as such don't have this problem on the Nexus. I've noticed the Huawei P8 Lite continues to scan in the background and it seems there is nothing you can do to stop it.
To demonstrate the problems I've made a very simple and clean app that exercise the Bluetooth LE functionality on a phone and used it to demonstrate this problem and also the P8 is broken. The app is available here: https://play.google.com/store/apps/details?id=eu.millibit.bluetootherror
Source is available here: https://bitbucket.org/millibit/eu.millibit.bluetootherror/src/master/
I hope I over time can extend this app to make it a test vehicle for Android documenting all the stange behavior from Android and collect it in a database. In case you are interested in contributing, don't hesitate to drop me a mail on bt.error#millibit.dk
The Android Bluetooth stack has a design flaw in its API. When you connect to a specific device by Bluetooth Device Address, there is no way to tell if you mean a Public address or Random address.
If you start to connect to a device with autoConnect=false which is not bonded and has not recently been seen in a Scan, it will assume you mean a Public address. So if you try to connect to a device having a static random address, it will fail.
To be sure you connect with the correct address type if the device is not bonded, you MUST perform a scan first, find the device and THEN start the connection attempt.
I am scanning for Bluetooth LE devices and running as a Peripheral (running Android 6.0 on a Moto G 2nd Gen)
The problem I am having is that sometimes (randomly it seems but often) it will not find any of my other peripheral devices, the other times it works fine.
I have a companion iOS device running similar code (both scanning for peripherals and acting as a peripheral), and when the Android scanning can't find the iOS device, my iOS finds the Android device acting as a peripheral just fine. So it seems only to be a problem with the scanning side of things.
It's not only just not finding my companion iOS device, but doesn't find any Bluetooth devices. When it works, it finds my companion iOS device as well as a bunch of other devices.
I have tried it with and without ScanFilters, and get the same issue.
I am building against SDK 26 with a minimum SDK of 23.
I am setting the permissions that are needed, as it sometimes works.
Relevant code below:
private void startScanning() {
mHandler = new Handler(mContext.getMainLooper());
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setReportDelay(0)
.build();
mBluetoothLeScanner.startScan(null, settings, mScanCallback);
}
}, 1000);
}
private ScanCallback mScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
super.onScanResult(callbackType, result);
if( result == null || result.getDevice() == null )
return;
Log.e("myTest", "Found Device");
BluetoothDevice device = result.getDevice();
final String deviceAddress = device.getAddress();
List<ParcelUuid> parcel = result.getScanRecord().getServiceUuids();
if (parcel != null) {
String parcelUUID = parcel.toString().substring(1,37);
if (parcelUUID.equalsIgnoreCase(mContext.getString(R.string.service_uuid))) {
final BluetoothDevice bleDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
if (!seenPeripherals.contains(deviceAddress)) {
stopScanning();
mHandler = new Handler(mContext.getMainLooper());
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
Log.e("AppToApp", "Trying to connect to device " + deviceAddress);
mGatt = bleDevice.connectGatt(mContext, false, mGattCallback);
}
}, 1000);
}
}
}
}
}
I face the same issue. This is because Google policy has been changed for Marshmallow API 23 and higher version, to use BLE user need to turn ON GPS. For Google Docs check this Permission # Runtime link. To fix it you have to enable "Location" in the settings of the phone as well as request location permission in the app at Runtime. Both need to be done for scanning to work properly.
To request the location permission put the following in a dialog or the likes:
myActivity.requestPermissions(new String[]{Manifest.permission.ACCESS_COURSE_LOCATION}, yourPermissionRequestCode);
and implement:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] Results){
if(requestCode == yourPermissionRequestCode)
{
... //Do something based on Results
}
}
in myActivity handle whatever the user selects. You also need to do the following to turn on your device's location services:
Intent enableLocationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
myActivity.startActivityForResult(enableLocationIntent, yourServiceRequestCode);
You can check if the user turned on the location services by implementing:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == yourServiceRequestCode)
{
...//Do whatever you need to
}
}
in myActivity. You can also manually turn on location services by doing:
Enter phone settings -> Select "Apps" -> Select your app -> Select the "Permissions" option -> Switch the "Location" permission on.
Once the user has enabled the permission and started location services then you could start scanning for peripherals. I've noticed that if you are already scanning while you enable the permission/turn on the location service it will still not put anything in your onScanResults
This allow companies to see your location and direct you to where they want.
while SCANNING for device, Once you are connected to the BLE device you can Turn Off the location service on your phone and you will still stay connected to your peripheral device. However, once you connected to a firmware (peripheral) you cannot then connect to any new peripheral until you disconnect the connection to the paired device, and all other scanning devices(mobile) cannot see the peripheral device name in their scanned list (when user search for near by peripheral device) when the peripheral is already connected to any other mobile device, because a peripheral can be connect to only 1 device at a time.
For BLE basic sample you can check this Truiton Ble tutorial. This snippet will fix your Issue I think. Happy coding :)
It might just simply be the case that the Android phone has a crappy Bluetooth chip. Have you looked at the hci log? Or logcat?
Bluetooth 4.0 chips (which is in your moto g) have strict limitations that you can't be a central and a peripheral at the same time, even though scanning should be allowed all the time. Therefore I wouldn't make a product that depends on the peripheral feature in Android until BT 4.0 is phased out.
You should test with a newer phone that has at least a Bluetooth 4.1 chip.
This question is related to something I posted before. Check these links
https://stackoverflow.com/a/39084810/3997720, https://stackoverflow.com/a/39597845/3997720
You need two methods: one for older api and one for newest api.
As for SDK 23 and up, You have to request run time permissions. Ask for location permission.
If you're using the app for non-commercial purposes (meaning expecting less than 5K users), you can use P2Pkit.
It uses P2P wifi connection in addition to BLE and non-BLE bluetooth, on older versions of android, and actually gets great results on discovery of nearby phones.
Upsides are it works on IOS too, and it has a fairly simple interface.
Downside is over 5K users you have to pay..
Background:
I have a BLE peripheral with two modes: "Application" and "Bootloader". In both modes, the device advertises with the same MAC address.
To switch from one mode to the other, the BLE peripheral must reboot itself. In doing so, it has to disconnect any active BLE connection.
The BLE peripheral only stays in Bootloader mode for about 5 seconds. If nobody connects to it within that window, it switches to Application mode.
The Problem:
Android takes a very long time to reconnect to the BLE device, long enough that I'm missing the 5 second window. The raw code has a few layers down to the BluetoothGATT and BluetoothAdapter layers, but the sequence of calls boils down to:
BluetoothGattCharacteristic c = mCharacteristics.get(POWER_STATE_UUID);
c.setValue(SHUTDOWN_VALUE);
mBluetoothGatt.writeCharacteristic(c);
// Signalled by BluetoothGattCallback.onCharacteristicWrite
bleWriteCondition.await();
mBluetoothGatt.disconnect();
// Wait for the underlying layer to confirm we're disconnected
while( mConnectionState != BluetoothProfile.STATE_DISCONNECTED ) {
// Signalled by BluetoothGattCallback.onConnectionStateChange
bleStateCondition.await();
}
mBluetoothGatt.connect();
while (mConnectionState != BluetoothProfile.STATE_CONNECTED) {
// Signalled by BluetoothGattCallback.onConnectionStateChange
bleStateCondition.await();
if (bleStateCondition.stat != 0) {
break;
}
}
Am I going about this entirely the wrong way? I've tried calling close() on the BluetoothGatt instance, then generating a new one with BluetoothDevice.connectGatt, but I get the same extremely slow behavior.
I'm testing on a Samsung Galaxy S4, API level 21.
The problem here is that the gatt connect call issues a background connection request. It can take quite a long time for this call to result in a connection. A description of the two types of connection request is here : Direct vs Background connections
The absolute fastest way to get a connection is to do a scan and upon finding your device issue a direct connection request to it. As the scan has just found it, you know it is there and the connection will complete quickly. This is more complicated than your example code, but will be most effective given your small window. A scan is the most aggressive way to find a device. However, if you already have the device object, you could just call a direct connection request on the device.
Scans are issued using code like this :
scanner = bluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
filters = new ArrayList<ScanFilter>();
ScanFilter uuidFilter = new ScanFilter.Builder()
.setServiceUuid(YOUR_SERVICE_UUID).build();
filters.add(uuidFilter);
scanner.startScan(filters, settings, myScanCallback);
Upon finding your device (using the scan callback), issue a direct connection request via this method call :
myGatt = myDevice.connectGatt(this, false, myGattCallback);
The key part being the parameter of false. The connection request will time out in around 30s if the device is not found.
I want to connect my tablet to my phone using WiFi direct in order to send some data like pictures etc from my phone to tablet.
But I do not want my phone to discover it first i.e I don't wanted to use discoverPeers() method of WiFiP2pManger.
How can I achieve this goal?
In your phone, use createGroups(). This makes your phone become the groupOwner. Then call discoverPeers() in your tablet, it will find your phone without your phone calling discoverPeers().
In your phone:
wifiP2pManager = (WifiP2pManager) context.getSystemService(context.WIFI_P2P_SERVICE);
channel=wifiP2pManager.initialize(context,context.getMainLooper(),null);
wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.i(TAG,"Creating p2p group");
}
#Override
public void onFailure(int i) {
Log.i(TAG,"Creating group failed, error code:"+i);
}
});
In your tablet, discover peers, request peers and connect peers as normal
In order to establish a WiFi Direct connection both phones should be running WiFi Direct discovery. In other words, they will see each other when they are both scanning for WiFi direct connections at the same time. This is because the way WiFi Direct works is that when phones are scanning for WiFi Direct connections, they will negotiate with the other peers for the role of Access Point or Slave device. Hence both need to call discoverPeers() to become discoverable themselves and find nearby devices.
In your use case you could even build your application using wifi hotspot
This solution doesn't work. In Android both need to be on discovery mode in order to connect.