Android send data wifi

Data transfer between two Wifi devices

I have searched in Google. In Android 2.2 and sdk 8 how can I use SSID in a List in Android ? By using SSID should get specific wifi enabled device properties by programmatically. With that help, should transfer the data between two Wifi enabled devices in Android.

2 Answers 2

To send data in a meaningful manner between two Android devices you would use a TCP connection. To do that you need the ip address and the port on which the other device is listening.

For the server side (listening side) you need a server socket:

try < Boolean end = false; ServerSocket ss = new ServerSocket(12345); while(!end)< //Server is waiting for client here, if needed Socket s = ss.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush String st = input.readLine(); Log.d("Tcp Example", "From client: "+st); output.println("Good bye and thanks for all the fish :)"); s.close(); if ( STOPPING conditions)< end = true; >> ss.close(); > catch (UnknownHostException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >

For the client side you need a socket that connects to the server socket. Please replace «localhost» with the remote Android devices ip-address or hostname:

try < Socket s = new Socket("localhost",12345); //outgoing stream redirect to socket OutputStream out = s.getOutputStream(); PrintWriter output = new PrintWriter(out); output.println("Hello Android!"); BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); //read line(s) String st = input.readLine(); //. . . //Close connection s.close(); >catch (UnknownHostException e) < // TODO Auto-generated catch block e.printStackTrace(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >

Источник

How to send data through wifi in android programmatically?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

package com.server.myapplication.server; import android.annotation.SuppressLint; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; @SuppressLint("SetTextI18n") public class MainActivity extends AppCompatActivity < ServerSocket serverSocket; Thread Thread1 = null; TextView tvIP, tvPort; TextView tvMessages; EditText etMessage; Button btnSend; public static String SERVER_IP = ""; public static final int SERVER_PORT = 8080; String message; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvIP = findViewById(R.id.tvIP); tvPort = findViewById(R.id.tvPort); tvMessages = findViewById(R.id.tvMessages); etMessage = findViewById(R.id.etMessage); btnSend = findViewById(R.id.btnSend); try < SERVER_IP = getLocalIpAddress(); >catch (UnknownHostException e) < e.printStackTrace(); >Thread1 = new Thread(new Thread1()); Thread1.start(); btnSend.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < message = etMessage.getText().toString().trim(); if (!message.isEmpty()) < new Thread(new Thread3(message)).start(); >> >); > private String getLocalIpAddress() throws UnknownHostException < WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); assert wifiManager ! = null; WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipInt = wifiInfo.getIpAddress(); return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress(); >private PrintWriter output; private BufferedReader input; class Thread1 implements Runnable < @Override public void run() < Socket socket; try < serverSocket = new ServerSocket(SERVER_PORT); runOnUiThread(new Runnable() < @Override public void run() < tvMessages.setText("Not connected"); tvIP.setText("IP: " + SERVER_IP); tvPort.setText("Port: " + String.valueOf(SERVER_PORT)); >>); try < socket = serverSocket.accept(); output = new PrintWriter(socket.getOutputStream()); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); runOnUiThread(new Runnable() < @Override public void run() < tvMessages.setText("Connected
"); > >); new Thread(new Thread2()).start(); > catch (IOException e) < e.printStackTrace(); >> catch (IOException e) < e.printStackTrace(); >> > private class Thread2 implements Runnable < @Override public void run() < while (true) < try < final String message = input.readLine(); if (message ! = null) < runOnUiThread(new Runnable() < @Override public void run() < tvMessages.append("client:" + message + "
"); > >); > else < Thread1 = new Thread(new Thread1()); Thread1.start(); return; >> catch (IOException e) < e.printStackTrace(); >> > > class Thread3 implements Runnable < private String message; Thread3(String message) < this.message = message; >@Override public void run() < output.write(message); output.flush(); runOnUiThread(new Runnable() < @Override public void run() < tvMessages.append("server: " + message + "
"); etMessage.setText(""); > >); > > >

Step 4 − Add the following code to androidManifest.xml

Читайте также:  Расчет пропускной способности wifi сети

Client

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to res/layout/MainActivity.java.

package com.client.myapplication.client; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; @SuppressLint("SetTextI18n") public class MainActivity extends AppCompatActivity < Thread Thread1 = null; EditText etIP, etPort; TextView tvMessages; EditText etMessage; Button btnSend; String SERVER_IP; int SERVER_PORT; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etIP = findViewById(R.id.etIP); etPort = findViewById(R.id.etPort); tvMessages = findViewById(R.id.tvMessages); etMessage = findViewById(R.id.etMessage); btnSend = findViewById(R.id.btnSend); Button btnConnect = findViewById(R.id.btnConnect); btnConnect.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < tvMessages.setText(""); SERVER_IP = etIP.getText().toString().trim(); SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim()); Thread1 = new Thread(new Thread1()); Thread1.start(); >>); btnSend.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < String message = etMessage.getText().toString().trim(); if (!message.isEmpty()) < new Thread(new Thread3(message)).start(); >> >); > private PrintWriter output; private BufferedReader input; class Thread1 implements Runnable < @Override public void run() < Socket socket; try < socket = new Socket(SERVER_IP, SERVER_PORT); output = new PrintWriter(socket.getOutputStream()); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); runOnUiThread(new Runnable() < @Override public void run() < tvMessages.setText("Connected
"); > >); new Thread(new Thread2()).start(); > catch (IOException e) < e.printStackTrace(); >> > class Thread2 implements Runnable < @Override public void run() < while (true) < try < final String message = input.readLine(); if (message ! = null) < runOnUiThread(new Runnable() < @Override public void run() < tvMessages.append("server: " + message + "
"); > >); > else < Thread1 = new Thread(new Thread1()); Thread1.start(); return; >> catch (IOException e) < e.printStackTrace(); >> > > class Thread3 implements Runnable < private String message; Thread3(String message) < this.message = message; >@Override public void run() < output.write(message); output.flush(); runOnUiThread(new Runnable() < @Override public void run() < tvMessages.append("client: " + message + "
"); etMessage.setText(""); > >); > > >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your both server and client application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Server:-

Client:-

Server:-

Click here to download the project code

Источник

Transfer Data between Android devices using wifi direct?

I have recently implement wifi direct into my project,my aim is pass string value between two wifidirect connected devices when some of my app condition satisfies.right now i have listed all peers and also made connection between the selected peer.what my idea is to pass a json file between the devices.so before try to execute that idea i try to pass a image file between two devices.i followed the steps from the android wifidirect tutorial.listing peers and the connection between the peers is success full but i cant pass the data between the devices.the follwing is my code. FileTransferService.java

package jing.app.directwifi; import android.app.IntentService; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; /** * A service that process each file transfer request i.e Intent by opening a * socket connection with the WiFi Direct Group Owner and writing the file */ public class FileTransferService extends IntentService < private static final int SOCKET_TIMEOUT = 5000; public static final String ACTION_SEND_FILE = "jing.app.directwifi.SEND_FILE"; public static final String EXTRAS_FILE_PATH = "file_url"; public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host"; public static final String EXTRAS_GROUP_OWNER_PORT = "go_port"; public FileTransferService(String name) < super(name); >public FileTransferService() < super("FileTransferService"); >/* * (non-Javadoc) * @see android.app.IntentService#onHandleIntent(android.content.Intent) */ @Override protected void onHandleIntent(Intent intent) < Context context = getApplicationContext(); if (intent.getAction().equals(ACTION_SEND_FILE)) < String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH); String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS); Socket socket = new Socket(); int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT); try < // Log.d(WiFiDirectActivity.TAG, "Opening client socket - "); socket.bind(null); socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT); Log.d("connected", "Client socket - " + socket.isConnected()); OutputStream stream = socket.getOutputStream(); ContentResolver cr = context.getContentResolver(); InputStream is = null; try < is = cr.openInputStream(Uri.parse(fileUri)); >catch (FileNotFoundException e) < Log.d("exp", e.toString()); >MainActivity.copyFile(is, stream); Log.d("exp" ,"Client: Data written"); > catch (IOException e) < Log.e("exp", e.getMessage()); >finally < if (socket != null) < if (socket.isConnected()) < try < socket.close(); >catch (IOException e) < // Give up e.printStackTrace(); >> > > > > > 
package jing.app.directwifi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Collection; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.p2p.WifiP2pConfig; import android.net.wifi.p2p.WifiP2pDevice; import android.net.wifi.p2p.WifiP2pDeviceList; import android.net.wifi.p2p.WifiP2pInfo; import android.net.wifi.p2p.WifiP2pManager; import android.net.wifi.p2p.WifiP2pManager.ActionListener; import android.net.wifi.p2p.WifiP2pManager.Channel; import android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener; import android.net.wifi.p2p.WifiP2pManager.PeerListListener; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.Settings; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, ConnectionInfoListener < private WifiP2pManager mManager; private Channel mChannel; private BroadcastReceiver mReceiver; private IntentFilter mIntentFilter; private Button mDiscover; private TextView mDevices; public ArrayAdapter mAdapter; private ArrayListmDeviceList = new ArrayList(); protected static final int CHOOSE_FILE_RESULT_CODE = 20; int flag=0; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDiscover = (Button) findViewById(R.id.discover); mDiscover.setOnClickListener(this); mDevices = (TextView) findViewById(R.id.peers); mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); mChannel = mManager.initialize(this, getMainLooper(), null); mReceiver = new WiFiDirectReceiver(mManager, mChannel, this); mIntentFilter = new IntentFilter(); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); >@Override protected void onResume() < super.onResume(); registerReceiver(mReceiver, mIntentFilter); >@Override protected void onPause() < super.onPause(); unregisterReceiver(mReceiver); >@Override public boolean onCreateOptionsMenu(Menu menu) < getMenuInflater().inflate(R.menu.activity_main, menu); return true; >private class WiFiDirectReceiver extends BroadcastReceiver < private WifiP2pManager mManager; private Channel mChannel; private MainActivity mActivity; public WiFiDirectReceiver(WifiP2pManager manager, Channel channel, MainActivity activity) < super(); mManager = manager; mChannel = channel; mActivity = activity; >@Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) < int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) < String title = "ANDROID_ID[" + getAndroid_ID() + "]"; title += " MAC[" + getMACAddress() + "]"; Toast.makeText(mActivity, "Wi-Fi Direct is enabled."+title, Toast.LENGTH_SHORT).show(); >else < Toast.makeText(mActivity, "Wi-Fi Direct is disabled.", Toast.LENGTH_SHORT).show(); >> else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) < if (mManager != null) < mManager.requestPeers(mChannel, new PeerListListener() < @Override public void onPeersAvailable(WifiP2pDeviceList peers) < if (peers != null) < mDeviceList.addAll(peers.getDeviceList()); ArrayListdeviceNames = new ArrayList(); for (WifiP2pDevice device : mDeviceList) < deviceNames.add(device.deviceName); >if (deviceNames.size() > 0) < mAdapter = new ArrayAdapter(mActivity, android.R.layout.simple_list_item_1, deviceNames); if(flag==0) < flag=1; showDeviceListDialog(); >> else < Toast.makeText(mActivity, "Device list is empty.", Toast.LENGTH_SHORT).show(); >> > >); > > else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) < >else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) < >> > @Override public void onClick(View v) < switch (v.getId()) < case R.id.discover: onDiscover(); break; >> private void onDiscover() < mManager.discoverPeers(mChannel, new ActionListener() < @Override public void onSuccess() < Toast.makeText(MainActivity.this, "Discover peers successfully.", Toast.LENGTH_SHORT).show(); >@Override public void onFailure(int reason) < Toast.makeText(MainActivity.this, "Discover peers failed.", Toast.LENGTH_SHORT).show(); >>); > private void showDeviceListDialog() < DeviceListDialog deviceListDialog = new DeviceListDialog(); deviceListDialog.show(getFragmentManager(), "devices"); >private class DeviceListDialog extends DialogFragment < @Override public Dialog onCreateDialog(Bundle savedInstanceState) < AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("Select a device") .setSingleChoiceItems(mAdapter, 0, MainActivity.this) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() < @Override public void onClick(DialogInterface dialog, int which) < dialog.dismiss(); >>); return builder.create(); > > @Override public void onClick(DialogInterface dialog, int which) < onDeviceSelected(which); dialog.dismiss(); >private void onDeviceSelected(int which) < WifiP2pDevice device = mDeviceList.get(which); if (device == null) < return; >WifiP2pConfig config = new WifiP2pConfig(); config.deviceAddress = device.deviceAddress; mManager.connect(mChannel, config, new ActionListener() < @Override public void onSuccess() < Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_FILE_RESULT_CODE); >@Override public void onFailure(int reason) < Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_SHORT).show(); >>); > /** * ANDROID_ID */ private String getAndroid_ID() < return Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID); >/** * Wi-Fi MAC */ private String getMACAddress() < WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo wifiInfo = manager.getConnectionInfo(); String mac = wifiInfo.getMacAddress(); // After the group negotiation, we assign the group owner as the file // server. The file server is single threaded, single connection server // socket. new FileServerAsyncTask(getApplicationContext()) .execute(); return mac; >@Override public void onActivityResult(int requestCode, int resultCode, Intent data) < // User has picked an image. Transfer it to group owner i.e peer using // FileTransferService. Uri uri = data.getData(); Log.d("intent", "Intent----------- " + uri); Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class); serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE); serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS, getMACAddress()); serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988); startService(serviceIntent); >/** * A simple server socket that accepts connection and writes some data on * the stream. */ public static class FileServerAsyncTask extends AsyncTask  < private Context context; /** * @param context * @param statusText */ public FileServerAsyncTask(Context context) < this.context = context; >@Override protected String doInBackground(Void. params) < try < System.out.println("insideeeeeeeeeeeeeeeeeeeeeeee"); ServerSocket serverSocket = new ServerSocket(8988); Log.d("Server: Socket opened", "Server: Socket opened"); Socket client = serverSocket.accept(); Log.d("Server: connection done", "Server: connection done"); final File f = new File(Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis() + ".jpg"); File dirs = new File(f.getParent()); if (!dirs.exists()) dirs.mkdirs(); f.createNewFile(); Log.d("server: copying files ", "server: copying files " + f.toString()); InputStream inputstream = client.getInputStream(); copyFile(inputstream, new FileOutputStream(f)); serverSocket.close(); return f.getAbsolutePath(); >catch (IOException e) < Log.e("exp", e.getMessage()); System.out.println(":iooo:"+e); return null; >> /* * (non-Javadoc) * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(String result) < if (result != null) < Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + result), "image/*"); context.startActivity(intent); >> /* * (non-Javadoc) * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() < >> public static boolean copyFile(InputStream inputStream, OutputStream out) < byte buf[] = new byte[1024]; int len; long startTime=System.currentTimeMillis(); try < while ((len = inputStream.read(buf)) != -1) < out.write(buf, 0, len); >out.close(); inputStream.close(); long endTime=System.currentTimeMillis()-startTime; Log.v("","Time taken to transfer all bytes is : "+endTime); > catch (IOException e) < Log.d("exp", e.toString()); return false; >return true; > @Override public void onConnectionInfoAvailable(WifiP2pInfo info) < // TODO Auto-generated method stub Toast.makeText(getApplicationContext(), "connectioninfoo", 3000).show(); >> 

where the the incomming data is begin accepted so when i need to execute this asyn thread,so anyone help me in which portion i have made the mistake.how can i transfer the file between devices .

Читайте также:  Сетевой адаптер wifi qualcomm atheros

Источник

How send data through WiFi?

In my Application I want to send files through WiFi to multiple users if they are using the same WiFi connection Without TCP. how to get the list of the users who are connected to a specified wify. I have tried with Samples But I didn’t get anything .

5 Answers 5

Wi-Fi peer-to-peer (P2P) allows Android 4.0 (API level 14) or later devices with the appropriate hardware to connect directly to each other via Wi-Fi without an intermediate access point (Android’s Wi-Fi P2P framework complies with the Wi-Fi Alliance’s Wi-Fi Direct™ certification program). Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi P2P, then communicate over a speedy connection across distances much longer than a Bluetooth connection. This is useful for applications that share data among users, such as a multiplayer game or a photo sharing application

http://developer.android.com/guide/topics/connectivity/wifip2p.html You can also refer this link to know more about programmatically

TCP is a great transport for file transfers, I don’t think you’ll ever come up with a reason to not use TCP to begin with. There is also no fancy built-in file-transfer protocol that all Andriod devices can handle, so you’ll still need to develop a client.

Besides, robust and reliable discover is not entirely possible either without the devices having custom clients for your purposes installed. Each client would either need to actively disclose itself, or passively reply to requests.

Passive: each device can be «ping»ed using actual ICMP (does not mean it’s an enabled device), TCP or UDP packets on the local subnet. Responding clients can thus be discovered bit by bit, and even share their scan results.

Читайте также:  Нужен ли драйвер вай фай

Active: a reverse approach would be to have each enabled client send out multicast datagrams and listen to them (similar to how ARP discovery works). See: http://developer.android.com/reference/java/net/MulticastSocket.html

Each client would then listen for incoming TCP connections with your file data and meta data in some structured, serialized manner and be ready to store and/or process these. Bonus points for authentication and authorization.

The enabled client approach (a device with a client), means that you can potentially develop cross-platform clients and have them talk to one another using your own discover and data transfer protocols.

Источник

Оцените статью
Adblock
detector