How to get Device name of your PEER using WifiP2P in Android - android

I am connecting two devices using wifi p2p from Android. I would like to know if there is any way for both devices to know the name of each other when the connection is established. When the device is starting the connection request, it is easy because you choose the peer from the list so you see the name. The question is focus to the device that receives the connection request!!!
I guess it has to be possible since the first time you try to connect you see a pop up with the name of the peer to accept the connection. But I don't know where this information can be found when programming an app.
I guess it has to be stored either in NetworkInfo (when you received a change of state) or in WifiP2pInfo (when the connection info is available).

When you receive the WIFI_P2P_CONNECTION_CHANGED_ACTION broadcast, if you are on API level 18 or higher, there is an extra in the intent, called EXTRA_WIFI_P2P_GROUP.
EXTRA_WIFI_P2P_GROUP
This returns a WifiP2pGroup on which you can call getClientList(). This gives you a collection of WifiP2pDevices. Once you have a WifiP2pDevice you can just get the field "deviceName".

Getting peer name is straight forward. Once you get the device list
public String getName(WifiP2pDevice device){
return device.deviceName;
}
Not sure if this is what you are asking for, pardon me if this is not the answer.

There is requestConnectionInfo method by this you can get all information about connected deivce simply implement this after connection is made like below
wifiManager.requestConnectionInfo(wifichannel, new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
//by info you can get host address and isGroupowner or else information you to
implement your code after this
}

Related

Which method is called when someone tries to connect using WifiP2PManager.connect(Channel, WifiP2pConfig,ActionListener)?

I am tring to setup WIFI P2P on 2 devices using
manager.addLocalService(channel, service, ActionListener)
and then connect both devices using
manager.connect(channel, config, ActionListener).
I would like to know which method is called before the popup to accept/reject connection is shown on the target device. All I was able to find was onConnectionInfoAvailable(WifiP2pInfo p2pInfo), but it is called after the connection is established.
I basically want to receive the "instance name" of the device trying to connect to me using WIFI P2P and then reject the connection request without showing system dialog(that allows the user to accept/reject connection).
I can't anything that can help me do this on docs or any other place. If anyone knows how to do it or can point me in the right direction then please let me know.
I solved it. I can put the instancename and devicename (of device I want to connect to) in Map that is passed when setting up service. From other device I can retrieve map of all devices available using this and find the instancename of one I need.

TXT Record from a Wifi Direct Printer

I'm trying to get TXT Records from Wifi Direct Printers nearby. So far, I can discover peers and establish a connection. But no luck with TXT Records.
I tried Wifi Direct Service Discovery, and I believe I did everything properly since I compared lots of codes from different resources including sample projects from Google and some open source Wifi Direct Wrappers in GitHub. But I couldn't make it work.
I've also seen some weird issues while trying to achieve that. e.g in some devices, when I start the peer discovery, Wifi Connection started to be turned off and on constantly.
Can someone explain how this actually works ? are DnsSdServiceResponseListener and DnsSdTxtRecordListener made for Android devices rather than Printers ?
I've also tried to listen the MultiCast DNS IP Address (224.0.0.251) with a MulticastSocket after establishing the connection between Android and Wifi Direct Printer, but I couldn't receive any data as well.
Thanks.
I used "DnsSdServiceResponseListener" and "DnsSdTxtRecordListener" successfully in my current project. Both listeners are associated to discovering local services nearby.
To use them properly, you have to do the following:
Implement your listeners
WifiP2pManager.DnsSdServiceResponseListener dnsListener = new WifiP2pManager.DnsSdServiceResponseListener() {
#Override
public void onDnsSdServiceAvailable(String instanceName, String registrationType, WifiP2pDevice device) {
// instanceName is service name and device is the print information
}};
WifiP2pManager.DnsSdTxtRecordListener txtListener = new WifiP2pManager.DnsSdTxtRecordListener() {
#Override
public void onDnsSdTxtRecordAvailable(String fullDomain, Map record, WifiP2pDevice device) {
// here we get the service published information in the record map object
}};
Add the listeners to your WiFiManager object
wifiP2PManagerObj.setDnsSdResponseListeners(mChannel, dnsListener, txtListener);
Add service request
WifiP2pDnsSdServiceRequest serviceRequest = WifiP2pDnsSdServiceRequest.newInstance();
wifiP2PManagerObj.addServiceRequest(mChannel,serviceRequest, actionListener);
Finally, discover services
wifiP2PManagerObj.discoverServices(mChannel,actionListener);
After discover services is executed successfully, the listeners should receive the nearby services information.
Hope this helps.
Goodluck.
Update
Wifi direct supported printers don't have any published services by default. To use them you have to connect to them via wifi direct and print normally as its a printer connected to your network. Note that those listeners are meant to capture published services (i.e will not capture anything for any device unless its publishing a service).
I think you will need to run Bonjour discovery once the connection is established. You can see NSD and look for "_ipp._tcp" as the service type. By the way,
for "I've also seen some weird issues while trying to achieve that. e.g in some devices, when I start the peer discovery, Wifi Connection started to be turned off and on constantly." if you're testing on a 7.1 device you might be seeing this issue, for which a patch should be coming soon.

Android: Nearby api, No Connection

I am attempting to get Google Nearby API working on my handset (an s5).
I am building and running the stock project from github Google Nearby API GIT.
The app builds and runs, with no errors. Having exported the app onto two S5s (amongst other handsets I have attempted to test it with) and connecting to a WLAN from a D-Link DSL-3680. Multicasting is enabled and set to v3.
However the app refuses to connect with the neighbouring phone when corresponding 'advertise' and 'discover' instructions have been given.
Is there an effective way in which to debug this behaviour? If I can provide an effective information dump of information that might help someone identify the issue then please let me know how.
What do you mean by 'refuse to connect'?
are you getting connection status- 'Rejected'?
If you are able to advertise and discover other devices, I'm assuming all your base conditions (like connected to local network) are fulfilled
Now,
You can try logging your status in Connection call back when you try to connect
Nearby.Connections.sendConnectionRequest(mGoogleApiClient, myName,
remoteEndpointId, myPayload, new Connections.ConnectionResponseCallback() {//response conditions}
using--
inside connection callback function write
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
similarly, if you are not doing this, you need to accept the connection request
Nearby.Connections.acceptConnectionRequest(mGoogleApiClient, remoteEndpointId, myPayload, this)
and inside Onresult callback add-
if(status.isSuccess()){
// Successful connection
} else {
// Failed connection
}
Hope it helped

How to programmatically check connection state of a Bluetooth device in Android?

I can enumerate the paired Bluetooth devices, and I need to check their current connection state on app startup.
But, I found no way of getting the connection state ?!
Here are some efforts I've tried but failed:
android.bluetooth.BluetoothDevice
It has the method to get the bond state of the remote device, and possible values for the bond state are: BOND_NONE, BOND_BONDING, BOND_BONDED. But it's not the connection state.
android.bluetooth.BluetoothProfile
The method can be used to get the connection state, but the BluetoothProfile object must be obtained first.
public abstract int getConnectionState (BluetoothDevice device);
As describe in doc: "Clients should call getProfileProxy(Context, BluetoothProfile.ServiceListener, int), to get the Profile Proxy.", it can ONLY be retrieve in a ServiceListener called when state changes.
What if I query the state on startup without any state changes happen yet?
android.bluetooth.BluetoothManager
It provides a method:
public int getConnectionState (BluetoothDevice device, int profile);
But it cannot be used to detect connection state of a Bluetooth speaker, as the profile argument only accepts GATT or GATT_SERVER (for low energy device), other profiles (HEADSET, HEALTH, A2DP) are not supported.
android.bluetooth.BluetoothAdapter
It provides a method:
public int getProfileConnectionState (int profile);
This function can be used to check whether the local Bluetooth adapter is connected to any remote device for a specific profile. It can be used to check a specified profile. But it cannot be used to check a given device.
Does anyone know how to get the connection state of a given Bluetooth device?
Thanks in advance.
See the notes in the answer from similar question How to programmatically tell if a Bluetooth device is connected? (Android 2.2):
There is no way to retrieve a list of connected devices at application startup. The Bluetooth API does not allow you to QUERY, instead it allows you to listen to CHANGES.
A hoaky work around to the above problem would be to retrieve the list of all known/paired devices... then trying to connect to each one (to determine if you're connected).
Alternatively, you could have a background service watch the Bluetooth API and write the device states to disk for your application to use at a later date.

How to create an autonomous GO for Wifi Direct in Android with dedicated ssid and passphrase?

I am trying to create a WI-FI Direct network with say 3 tablet PCs. I want to run WiFi-Direct as background service, with one device set as autonomous GO. Could someone please tell me how can this be done in Android? Also someone please tell me how we can set dedicated SSID and passphrase so that any time new devices are added to this network, they can search for a specific ssid and passphrase for connection establishment during the application initiation ?
I am using Android API Level 18 for my development ...
Thanks in advance ...
This is how an autonomous Group Owner is created i.e. using the following code you can deliberately set a device in Wifi direct Network as a Group Owner
manager.createGroup(channel,new WifiP2pManager.ActionListener()
{
#Override
public void onSuccess()
{
Toast.makeText(WiFiDirectActivity.this, "Group Created",Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason)
{}
});
You can use this code on any event like Button click etc.
Bluemoon10 was almost right. I can't comment yet because I need 50 reputation :/. The config.groupOwnerIntent ranges from 1-15 with 15 being the highest intent to be group owner.
If 2 devices try to connect with both GO intents == 15, the connect call will fail. If there is a GO intent tie lower than 15, the devices agree on a tie breaker bit and will succeed. So if you want one device to be group owner, you have to make sure that it is the only one trying to be. You can do this with Service Discovery, i.e. if there is a service running set your GO intent to 15 on the device with the service and 1 on the connecting device. Only one device needs to call connect to initiate connection.
Link to Service Discovery tutorial: http://developer.android.com/training/connect-devices-wirelessly/nsd-wifi-direct.html
To create autonomous group you can just invoke createGroup() method from your manager. In order to set ssid and passPhrase you must invoke the hidden methods of WifiP2pGroup class setPassphrase and setNetworkName.
To achieve that, you use java reflection. Try the following example.
Let us assume WifiP2pGroup group your current object.
Method
setPassPhraseMethod=group.getClass().getMethod("setPassphrase", new Class[ {String.class});
and now you invoke the method:
setPassPhraseMethod.invoke(group, "yourNewPassPrhase");
hope it is helpful.
Normally the Group Owner is decided by the WiFi Direct protocol.
However you can force it's hand by, using the config class.
final WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress=myDeviceAddr;
config.wps.setup = WpsInfo.PBC;
config.groupOwnerIntent =15;
In this case I think I'm correct in saying that 15 mean least likely to become GO, you set this to zero, if you want that device to be the GO.
Also this might be where you can set pin etc take a look at WpsInfo.
this config info in then passed into your connect call.
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener().
Hope this helps.

Categories

Resources