Android wifi直接聊天应用程序仅在第一时间工作

时间:2019-06-19 00:21:28

标签: android

我正在尝试开发一个wifi直接聊天应用程序,并且它工作正常(发现对等体,连接对等体,发送和接收消息),但是存在问题...我正在使用平板电脑android版本5,例如客户端和我正在像主机一样使用三星g6 android8。我第一次从平板电脑(客户端)向手机(主机)发送味精,它工作正常,并且发送消息正常,但是如果我关闭并重新启动应用程序,则第二次没有从客户端(平板电脑)发送消息到主机(主机),没有错误! olso,如果我使tablet(client)处于暂停模式或关闭屏幕,并且我进入该应用程序,它将无法发送...。为什么我有此问题...

====================WiFiDirectBroadcastReceiver class========================

package com.Sharpsoft.wifip2p;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.widget.Toast;

public class WiFiDirectBroadcastReceiver extends BroadcastReceiver 
{
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity mActivity;

public WiFiDirectBroadcastReceiver(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)){
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)){
//do something
if(mManager!=null)
{
mManager.requestPeers(mChannel,mActivity.peerListListener);
}
}else 

if
(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) 
{
//do something
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)) 
{
//do something
}}}




=========================Mainactivity class================================

package com.Sharpsoft.wifip2p;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
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.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

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 WiFiDirectBroadcastReceiver(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(final byte[] bytes){

new thread(new runnable(){ 
@override 
public void run(){
try {
outputstream.Write(bytes);
} 
catch(ioexeption ex)
{
ex.Printstacktrace();
}}}).
Start();

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();
}
}
}
}

wifi direct chat app image

没有错误,但应用程序只能在第一次将消息从客户端(平板电脑)发送到主机(电话)...第二次不能没有错误地发送消息

0 个答案:

没有答案