How to get wifi direct devices name from WifiP2pDeviceList - java

I want to get the wi-fi direct name when I execute request peers, here is my code:
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
Log.d(tag, "success discover the peers ");
if (mManager != null) {
mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
// TODO Auto-generated method stub
if (peers != null) {
if (device.deviceName.equals("ABC")) {
Log.d(tag, "found device!!! ");
Toast.makeText(getApplicationContext(), "FOUND!!", Toast.LENGTH_SHORT).show();
}
}
}
});
} else {
Log.d(tag, "mMaganger == null");
}
}
I want to get the deviceName from the list of peers so that I can found that one named "ABC". Any idea?

If you want others device name:
wifiP2pManager.requestPeers(wifiChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList wifiP2pDeviceList) {
for (WifiP2pDevice device : wifiP2pDeviceList.getDeviceList())
{
if (device.deviceName.equals("ABC")) Log.d(tag, "found device!!! ");
// device.deviceName
}
}
});
If you want your device name get it in the receiver:
if (action.equals(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION))
{
WifiP2pDevice device = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
// device.deviceName
}
If you want to change device name:
try {
Method method = wifiP2pManager.getClass().getMethod("setDeviceName",
WifiP2pManager.Channel.class, String.class, WifiP2pManager.ActionListener.class);
method.invoke(wifiP2pManager, wifiChannel, "New Device Name", new WifiP2pManager.ActionListener() {
public void onSuccess() {}
public void onFailure(int reason) {}
});
} catch (Exception e) {}

You have the object for WifiP2pDeviceList(peers)
Call the method getDeviceList() on peers which returns a collection(list) of P2p devices Collection<WifiP2pDevice>
Then iterate through the collection element which is a WifiP2pDevice and it would contain the deviceName property which is what you need exactly.
Refer this training from android developers
Hope you are able to get it

Related

BLE on tinyB java characteristic has no notify

i`m trying to connect simple device(AB Shutter3) to java application on PC, but get no notification till connect. For test try
BluetoothDevice currentDev = (BluetoothDevice) container.getDevice();
currentDev.setTrusted(true);
if(!currentDev.getConnected()) {
currentDev.connect();
}
logger.info(currentDev.getName());
then get ALL services, descriptors and try to enable notifications like:
public void findServiceAndCharacteristic(BlueToothDeviceContainer container, String serviceUid){
for (BluetoothGattService service : container.getGattServices()) {
if(service.getUUID().equals(CUSTOM_SHUTTER_SERVICE_2.value) ||
service.getUUID().equals(CUSTOM_SHUTTER_SERVICE.value) ||
service.getUUID().equals(GENERAL_DEVICE_INFORMATION.value)){
List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics();
for(BluetoothGattCharacteristic ch : characteristics){
logger.info(ch.getUUID());
try {
List<BluetoothGattDescriptor> descrs = ch.getDescriptors();
for(BluetoothGattDescriptor ds : descrs){
ds.enableValueNotifications(new BluetoothNotification<byte[]>() {
#Override
public void run(byte[] bytes) {
logger.info(ds.getUUID() + "getted");
logger.info("BUTTON WAS PUSHED!!!");
}
});
}
} catch (BluetoothException ex){
logger.warn(ch.getUUID() + " does not work.");
}
try{
BluetoothNotification btnm = new BluetoothNotification<byte[]>() {
#Override
public void run(byte[] bytes) {
logger.info(ch.getUUID() + "getted CH");
logger.info("BUTTON WAS PUSHED!!!");
}
};
ch.enableValueNotifications(btnm);
} catch (BluetoothException ex){
logger.warn(ch.getUUID() + " does not work.");
}
}
but run method does not work. What am i doing wrong, does anybody knows?
Problem was not at library. Problem at HID characteristic. It was not found on device, so there was no notifications from it.

Moving to next activity once my QR Code has been scanned

I have limited Android Experience and had a very basic doubt. My scenario is as follows:
I currently have 2 applications, one being a QR Code Scanner and another which displays a QR Code. These will be running on multiple devices. The communication steps which take place are as follows:
Prior Setup:
There is a firebase database containing strings for QR Codes to be generated.
Device 2 reads the Code off the Firebase Database and displays it on the Screen (2nd App).
Device Communication:
Device 1 has the Scanner App and Device 2 has the QR Code displayed on Screen.
Device 1 now scans the QR Code from the Device 2 and verifies through some logic whether QR Code is valid or not.
If QR Code is valid, then the following takes place:
Device 1 calculates a new QR Code and places it on the Firebase Database.
The Device 2 should now move from displaying the QR Code to another activity which has the logic to Scan QR Codes of other Devices and verifies if they are correct.
Device 3 onwards must display a new QR Code which is on the Firebase Database which can now be scanned by Devices 1 and 2.
Note: The QR Code Updates on UI must keep happening until there is some sort of indication which makes the Device move to the QR Code Scanning stage.
Things which are working:
The 2 activities of the application (QR Code Display and QR Code Scanning) working independently.
QR Code Updates on UI whenever Firebase Database updated.
Things which are not working:
Moving from QR Code Display to Scanning once the QR Code is deemed valid.
Things I have tried:
Creating a Server Socket Implementation on the QR Code Display Application which is running as a Service called by my Main Activity. Client Socket Implementation (placed as a Service) is on the QR Code Scanner, which will send data to the Listening Server Socket once the QR Code is deemed valid. (Issue is that neither data is sent nor received).
Creating a Server Socket Implementation on the QR Code Display Application which is running as a Service called by my Main Activity. Client Socket Implementation (placed on UI Thread) is on the QR Code Scanner, which will send data to the Listening Server Socket once the QR Code is deemed valid.(Issue is that neither data is sent nor received)
I am very confused as to whether my approach is correct. Is there a better way to do it? Code for my service is as follows:
Device 2 - QR Code Display App:
Service
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Client client;
#Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Client();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Display Server Implementation (Called T_Client)
public class T_Client extends Thread {
private static final String TAG = "T_Client";
private Socket sock = null;
private boolean running = false;
private ObjectInputStream in;
private ObjectOutputStream out;
private Object objIn;
public void send(String _msg) {
if (out != null) {
try {
out.writeObject(_msg);
out.flush();
Log.i("Send Method", "Outgoing : " + _msg.toString());
} catch (IOException ex) {
Log.e("Send Method", ex.toString());
}
}
}
public void stopClient() {
Log.v(TAG,"stopClient method run");
running = false;
}
#Override
public void run() {
running = true;
try {
ServerSocket sock1 = new ServerSocket(9999);
try {
Log.i(TAG, "C: Connected.");
while (running) {
sock = sock1.accept();
out = new ObjectOutputStream(sock.getOutputStream());
in = new ObjectInputStream(sock.getInputStream());
objIn = in.readObject();
Log.i("Object Read Class", objIn.getClass().toString());
Log.i("Object Read", objIn.toString());
/* Currently commented because startActivity not recognised
if (objIn != null) {
Intent dialogIntent = new Intent();
dialogIntent.setClass(this, MainActivity.class);
dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
Atleast the data should get read here
*/
System.out.println("Object Read Class" + objIn.getClass().toString());
System.out.println("Object Read" + objIn.toString());
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + objIn + "'");
} catch (Exception e) {
Log.e(TAG, "S: Error", e);
} finally {
out.close();
in.close();
sock.close();
Log.i(TAG, "Closing socket: " + sock);
}
} catch (Exception e) {
Log.e(TAG, "C: Error", e);
}
}
}
Intent intent=new Intent(getContext().getApplicationContext(),MyService.class);
getContext().startService(intent);
Scanner Application: (Written in Kotlin)
Scanner Client Implementation (Called T_Server)
internal class T_Server : Thread() {
private var sock: Socket? = null
private var running = false
private var out: ObjectOutputStream? = null
private val objIn: Any? = null
var blockchain_kotlin_copy = SecondActivity().blockchain_kotlin_copy
fun send(_msg: String) {
if (out != null) {
try {
out!!.writeObject(_msg)
out!!.flush()
Log.i("Send Method", "Outgoing : $_msg")
} catch (ex: IOException) {
Log.e("Send Method", ex.toString())
}
}
}
fun stopClient() {
Log.v(TAG, "stopClient method run")
running = false
}
override fun run() {
running = true
try {
val sock1 = ServerSocket(9999)
try {
Log.i(TAG, "C: Connected.")
while (running) {
sock = sock1.accept()
try {
out = ObjectOutputStream(sock!!.getOutputStream())
out!!.writeObject(blockchain_kotlin_copy)
out!!.flush()
out!!.reset()
Log.i("Send Method", "Outgoing : $blockchain_kotlin_copy")
println("Out is being sent")
println("$blockchain_kotlin_copy")
} catch (ex: IOException) {
Log.e("Send Method", ex.toString())
}
}
} catch (e: Exception) {
Log.e(TAG, "S: Error", e)
} finally {
out!!.close()
sock!!.close()
Log.i(TAG, "Closing socket: " + sock!!)
}
} catch (e: Exception) {
Log.e(TAG, "C: Error", e)
}
}
companion object {
private val TAG = "T_Server"
}
}
Service
public class MyService extends Service {
private static final String TAG = "MyService";
private T_Server client;
#Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
if (client != null) {
try {
client.stopClient();
} catch (Exception e) {
Log.e(TAG, "Error on close: " + e);
}
}
super.onDestroy();
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
client = new T_Server();
client.start();
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Main Activity
val intent = Intent(this, MyService::class.java)
this.startService(intent)
It sounds like you might be interested in Firebase Device-to-Device notification. You might do as follows
Device X displays QR code
Some Device Y reads the QR code from Device X and if(verified) sendNotificationToDevice(X)
Device X moves to Scanner activity to read from some other Device Z.
Besides the link above, there are a number of YouTube tutorials and Medium blog posts on how to implement Device-to-Device notification.

How do I output messages in ListView from PubNub method history()?

I have in my project (simple chat application) ListView of TextViews (messages). Here's code of publishing messages:
public void publish(View view) {
final EditText mMessage = (EditText) MainActivity.this.findViewById(R.id.new_message);
final Map<String, String> message = ImmutableMap.<String, String>of("sender", MainActivity.this.nickName, "message", mMessage.getText().toString(), "timestamp", DateTimeUtil.getTimeStampUtc());
MainActivity.this.mPubnub_DataStream.publish().channel(Constants.CHANNEL_NAME).shouldStore(true).message(message).async(
new PNCallback<PNPublishResult>() {
#Override
public void onResponse(PNPublishResult result, PNStatus status) {
try {
if (!status.isError()) {
mMessage.setText("");
Log.v(TAG, "publish(" + JsonUtil.asJson(result) + ")");
} else {
Log.v(TAG, "publishErr(" + JsonUtil.asJson(status) + ")");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
);
}
I'm trying to output messages from history:
this.mPubnub_DataStream.history()
.channel(Constants.CHANNEL_NAME)
.async(new PNCallback<PNHistoryResult>() {
#Override
public void onResponse(PNHistoryResult result, PNStatus status) {
}
});
I have no idea how to override onResponse method. Please help me.
Btw, I can check if my messages are stored, but output to terminal is not what I really need.
pubNub.history()
.channel(channelName)
.count(100)
.async(new PNCallback<PNHistoryResult>() {
#Override
public void onResponse(PNHistoryResult result, PNStatus status) {
for (int i = 0; i < 100; i++) {
System.out.println(result.getMessages().get(i).getEntry());
}
}
});
This is more of a UI data binding question than a PubNub question, as long as you actually receiving messages from the history call.
If you are then perhaps the sample code in this example app might be helpful: github.com/pubnub/webinar-android-intro

How to check if WebSocket is connected

I created a Websocket service class using KOUSH library https://github.com/koush/AndroidAsync#can-also-create-web-sockets
Now I want to check if the Websocket is connected to my server from my mainActivity. Do you know how I can check this?
thanks
AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
public void onDataAvailable(ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
});
You can do something like this:
if (mWebSocketClient.isOpen) {
mWebSocketClient.send(jObj.toString())
} else {
try {
client.connectWebSocket(p0)
mWebSocketClient.send(jObj.toString())
} catch (e : Exception){
Toast.makeText(p0, "not connected $e", Toast.LENGTH_LONG).show()
}
}
The solution is to save the result of this Function to a local Websocket Variable , and then you check its status :
WebSocket webSocket=null;
try {
webSocket=AsyncHttpClient.getDefaultInstance().websocket(get, "my-protocol", new WebSocketConnectCallback() {
#Override
public void onCompleted(Exception ex, WebSocket webSocket) {
if (ex != null) {
ex.printStackTrace();
return;
}
webSocket.send("a string");
webSocket.send(new byte[10]);
webSocket.setStringCallback(new StringCallback() {
public void onStringAvailable(String s) {
System.out.println("I got a string: " + s);
}
});
webSocket.setDataCallback(new DataCallback() {
public void onDataAvailable(ByteBufferList byteBufferList) {
System.out.println("I got some bytes!");
// note that this data has been read
byteBufferList.recycle();
}
});
}
}).get();
}catch(InterruptedException e){
//handle exception
}catch(ExecutionException e){
//handle exception
}
if(websocket!=null && websocket.isOpen()){
//websocket is working fine
}
you can use other statements like websocket.isClosed();

Invoke sendMessage method from second activity

I'm doing some dev for a Chromecast sender app, and I have this method in my MainActivity class:
public void sendMessage(String message) {
if (mApiClient != null && mHelloWorldChannel != null) {
try {
Cast.CastApi.sendMessage(mApiClient, mHelloWorldChannel.getNamespace(), message)
.setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status result) {
if (!result.isSuccess()) {
Log.e(TAG, "Sending message failed");
} else {
System.out.println("Message sent!");
}
}
});
} catch (Exception e) {
Log.e(TAG, "Exception while sending message", e);
}
} else {
if (mApiClient == null) {
System.out.println("apiClient null");
}
if (mHelloWorldChannel == null) {
System.out.println("mHello null");
}
}
}
Every works dandy and I can send messages to my Chromecast and do nifty things with them when they get there. However, I use a number of other Activities in my app, and I'd like to be able to send messages to the Chromecast from those as well.
That said, what is the best way to access this method from a second activity?
If you will define your method static one then you can call it like this:
ClassName.sendMessage(String message);
If it is not static one, you will need to create an object for it.
ClassName c= new ClassName(SomeconstructorParams);
c.sendMessage(String message);

Categories

Resources