Android - Passing Simple String Over Wi-fi?
I have Wi-fi direct demo. In that we can transfer any image files to other devices. When another device get connected and it shows to send image from gallery. And at other side it
Solution 1:
You can do something like this:
DeviceDetailFragment.java
@OverrideprotectedStringdoInBackground(Void... params) {
ServerSocket serverSocket = null;
Socket client = null;
DataInputStream inputstream = null;
try {
serverSocket = newServerSocket(8988);
client = serverSocket.accept();
inputstream = newDataInputStream(client.getInputStream());
String str = inputstream.readUTF();
serverSocket.close();
return str;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
returnnull;
}finally{
if(inputstream != null){
try{
inputstream.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(client != null){
try{
client.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
if(serverSocket != null){
try{
serverSocket.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
}
}
}
}
@OverrideprotectedvoidonPostExecute(String result) {
if (result != null) {
Toast.makeText(..., result, ...).show();;
}
}
FileTransferService.java
@OverrideprotectedvoidonHandleIntent(Intent intent) {
Contextcontext= getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
Stringhost= intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socketsocket=newSocket();
intport= intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
DataOutputStreamstream=null;
try {
socket.connect((newInetSocketAddress(host, port)), SOCKET_TIMEOUT);
stream = newDataOutputStream(socket.getOutputStream());
stream.writeUTF("a string");
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
Post a Comment for "Android - Passing Simple String Over Wi-fi?"