Для передачи и получения данных между двумя устройствами через wifip2p. Вам необходимо создать три threads.each для потока client, server и clientServer для передачи данных. Ссылаться на полный код.
Файл MainActivity.java: -
public class MainActivity extends AppCompatActivity {
Button btnOnOff, btnDiscover, btnSend;
ListView listView;
TextView read_msg_box, connectionStatus;
EditText writeMsg;
WifiManager wifiManager;
WifiP2pManager mManager;
WifiP2pManager.Channel mChannel;
BroadcastReceiver mReceiver;
IntentFilter mIntentFilter;
List<WifiP2pDevice> peers=new ArrayList<WifiP2pDevice>();
String[] deviceNameArray;
WifiP2pDevice[] deviceArray;
static final int MESSAGE_READ=1;
ServerClass serverClass;
ClientClass clientClass;
SendReceive sendReceive;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialWork();
exqListener();
}
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what)
{
case MESSAGE_READ:
byte[] readBuff= (byte[]) msg.obj;
String tempMsg=new String(readBuff,0,msg.arg1);
read_msg_box.setText(tempMsg);
break;
}
return true;
}
});
private void exqListener() {
btnOnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
btnOnOff.setText("ON");
}else {
wifiManager.setWifiEnabled(true);
btnOnOff.setText("OFF");
}
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
connectionStatus.setText("Discovery Started");
}
@Override
public void onFailure(int i) {
connectionStatus.setText("Discovery Starting Failed");
}
});
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
final WifiP2pDevice device=deviceArray[i];
WifiP2pConfig config=new WifiP2pConfig();
config.deviceAddress=device.deviceAddress;
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
Toast.makeText(getApplicationContext(),"Connected to "+device.deviceName,Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int i) {
Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
}
});
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String msg=writeMsg.getText().toString();
sendReceive.write(msg.getBytes());
}
});
}
private void initialWork() {
btnOnOff=(Button) findViewById(R.id.onOff);
btnDiscover=(Button) findViewById(R.id.discover);
btnSend=(Button) findViewById(R.id.sendButton);
listView=(ListView) findViewById(R.id.peerListView);
read_msg_box=(TextView) findViewById(R.id.readMsg);
connectionStatus=(TextView) findViewById(R.id.connectionStatus);
writeMsg=(EditText) findViewById(R.id.writeMsg);
wifiManager= (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mManager= (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel=mManager.initialize(this,getMainLooper(),null);
mReceiver=new WiFiDirectBroadCastReviever(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);
}
WifiP2pManager.PeerListListener peerListListener=new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
if(!peerList.getDeviceList().equals(peers))
{
peers.clear();
peers.addAll(peerList.getDeviceList());
deviceNameArray=new String[peerList.getDeviceList().size()];
deviceArray=new WifiP2pDevice[peerList.getDeviceList().size()];
int index=0;
for(WifiP2pDevice device : peerList.getDeviceList())
{
deviceNameArray[index]=device.deviceName;
deviceArray[index]=device;
index++;
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,deviceNameArray);
listView.setAdapter(adapter);
}
if(peers.size()==0)
{
Toast.makeText(getApplicationContext(),"No Device Found",Toast.LENGTH_SHORT).show();
return;
}
}
};
WifiP2pManager.ConnectionInfoListener connectionInfoListener=new WifiP2pManager.ConnectionInfoListener() {
@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
final InetAddress groupOwnerAddress=wifiP2pInfo.groupOwnerAddress;
if(wifiP2pInfo.groupFormed && wifiP2pInfo.isGroupOwner)
{
connectionStatus.setText("Host");
serverClass=new ServerClass();
serverClass.start();
}else if(wifiP2pInfo.groupFormed)
{
connectionStatus.setText("Client");
clientClass=new ClientClass(groupOwnerAddress);
clientClass.start();
}
}
};
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver,mIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
public class ServerClass extends Thread{
Socket socket;
ServerSocket serverSocket;
@Override
public void run() {
try {
serverSocket=new ServerSocket(8888);
socket=serverSocket.accept();
sendReceive=new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class SendReceive extends Thread{
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(Socket skt)
{
socket=skt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
byte[] buffer=new byte[1024];
int bytes;
while (socket!=null)
{
try {
bytes=inputStream.read(buffer);
if(bytes>0)
{
handler.obtainMessage(MESSAGE_READ,bytes,-1,buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientClass extends Thread{
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress)
{
hostAdd=hostAddress.getHostAddress();
socket=new Socket();
}
@Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd,8888),500);
sendReceive=new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
WiFiDirectBroadCastReviever.java class:
public class WiFiDirectBroadCastReviever extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public WiFiDirectBroadCastReviever(WifiP2pManager mManager, WifiP2pManager.Channel mChannel, MainActivity mActivity) {
this.mManager = mManager;
this.mChannel = mChannel;
this.mActivity = mActivity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if (state==WifiP2pManager.WIFI_P2P_STATE_ENABLED){
Toast.makeText(context,"wifi is on",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"wifi is off",Toast.LENGTH_SHORT).show();
}
}else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
if (mManager!=null){
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
}else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
if (mManager==null){
return;
}
NetworkInfo networkInfo=intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel,mActivity.connectionInfoListener);
}else {
mActivity.connectionStatus.setText("device disconnected");
}
}else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
// TODO: 19-Mar-19
}
}
}