Android Studio Wifi P2P работает не на всех устройствах - PullRequest
0 голосов
/ 28 марта 2020

Я был новичком в android, а также в стеке потока. я создаю приложение, используя учебник с youtube - "Android Учебник по WiFi P2P | Android Учебник по WiFi Direct Sarthi Technology" - url - https://www.youtube.com/watch?v=nw627o-8Fok&list=PLFh8wpMiEi88SIJ-PnJjDxktry4lgBtN3 работает нормально, отправка текста только с Android 6.0 только устройства версии, когда я пытаюсь Android 7 & 8, он только может получить от устройства Android 6.0, не может отправлять текст с устройств Android 7 или более поздней версии, App cra sh все время. Полностью не работает с Android Device 7 или 8 в качестве хоста и клиентского устройства Android 7 или 8. Работает полностью Только Android 6 устройств

   public void write(byte[] bytes) {

     int j = bytes.length;
        try {
            outputStream.write(bytes,0,j);

        } catch (IOException e) {
            e.printStackTrace();

        }
    }

App cra sh при вызове «outputStream.write», я пытаюсь использовать «outputStream.write (bytes);» Метод также это также Cra sh, я использую Android Studio 2.3.3

это основной код деятельности

public class MainActivity extends AppCompatActivity {
Button btnonoff ,btnDiscover,btnSend ;
ListView listView ;
TextView read_msg_box ,connectionStatus ;
EditText writemsg ;
WifiManager  WifiManager;
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel ;
BroadcastReceiver mReceiver ;
IntentFilter mInterntFilter ;
List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>() ;
String[] deviceNameArray ;
WifiP2pDevice[] devicearray ;

static final int MESSAGE_READ =1 ;

ServerClass serverClass ;
ClientClass clientClass ;
SendReceive sendReceive ;
private Object conditions;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initialwork();

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, 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 reason) {
            Toast.makeText(getApplicationContext(),"Not Connected",Toast.LENGTH_SHORT).show();
        }
    });



 }
 });

}
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 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.Connection) ;
    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);

    mInterntFilter = new IntentFilter();

    mInterntFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
    mInterntFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    mInterntFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
    mInterntFilter.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();
            }

        }
    };

public void SEND(View v) {
 String msg = writemsg.getText().toString();
sendReceive.write(msg.getBytes());
 }
public void ONOFF(View v) {
    if(WifiManager.isWifiEnabled())
    {
        WifiManager.setWifiEnabled(false);
        btnonoff.setText("OFF");
    }
    else
    {
        WifiManager.setWifiEnabled(true);
        btnonoff.setText("ON");
    }

}

public void search(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
        connectionStatus.setText(" Discovered");
    }

    @Override
    public void onFailure(int i) {
        connectionStatus.setText(" Discovering");
    }


});

}




@Override
protected void onResume() {
    super.onResume();
registerReceiver(mReceiver,mInterntFilter) ;

}

@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) {

     int j = bytes.length;
        try {
            outputStream.write(bytes,0,j);
            outputStream.flush();
        } 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();
    }

}

}
 }

это код WIFIDirectBroadcast -

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)) {
        // Determine if Wifi P2P mode is enabled or not, alert
        // the Activity.
        int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
        if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
           // activity.setIsWifiP2pEnabled(true);
            Toast.makeText(context, "Wifi ON", Toast.LENGTH_SHORT).show();
        } else {
          //  activity.setIsWifiP2pEnabled(false);
            Toast.makeText(context, "Wifi OFF", Toast.LENGTH_SHORT).show();
        }

    } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

        // The peer list has changed! We should probably do something about
        // that.
        if(mManager!=null)
        {
            mManager.requestPeers(mChannel , mActivity.peerListListener);
        }

    } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

        // Connection state changed! We should probably do something about
        // that.
        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)) {


     }

   }
}
...