简体   繁体   中英

How to make a consistent WIFI connection in android

In my new android app, I have made a direct tcp connection to a device with specific IP and port, all working fine. Issue here is when Wifi disconnect it does not reconnect or send data again.

Inside my code below, I have a class Client.java and MainActivity.java below.

How can I do this?

#####################################################

public class Client extends AsyncTask<String, Void, Void> {

    String dstAddress;
    int dstPort;
    String response = "";
    TextView textResponse;

    Socket socket = null; Socket smtpSocket = null;
    DataOutputStream os = null;
    DataInputStream is = null;



    Client(String addr, int port, TextView textResponse) {
        dstAddress = addr;
        dstPort = port;
        this.textResponse = textResponse;
    }

    @Override
    protected Void doInBackground(String... params) {




        String str = params[0];


        try {

            smtpSocket = new Socket(dstAddress, dstPort);
            os = new DataOutputStream(smtpSocket.getOutputStream());
            is = new DataInputStream(smtpSocket.getInputStream());


            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                    1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            InputStream inputStream = smtpSocket.getInputStream();

            //smtpSocket.


          /* notice: inputStream.read() will block if no data return */

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }

            //textResponse.setText(response);


        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");

        }

        if (smtpSocket != null && os != null ) {
                try {

                    os.writeBytes(str);

                    String responseLine;
                    while ((responseLine = is.readLine()) != null) {
                        System.out.println("Server: " + responseLine);

                        if (responseLine.indexOf("Ok") != -1) {
                            break;
                        }
                    }
                    //os.close();
                    //is.close();
                    //smtpSocket.close();
                } catch (UnknownHostException e) {
                    System.err.println("Trying to connect to unknown host: " + e);
                } catch (IOException e) {
                    System.err.println("IO-Exception:  " + e);
                }
        }


        return null;
    }




    @Override
    protected void onPostExecute(Void result) {
        //textResponse.setText("dweewed");
        super.onPostExecute(result);

        //super.cancel(true);
    }

    public void sendToPort(String str) throws IOException {
        if (smtpSocket != null && os != null ) {
            try {

                os.writeBytes(str);

               // os.close();
               // is.close();
               // smtpSocket.close();
            } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
            } catch (IOException e) {
                System.err.println("IOException:  " + e);
            }
        }




    }



}
#############################################################
MainActivity.java


public class MainActivity extends AppCompatActivity {

    Button buttonConnect, buttonClear;
    TextView response;

    Client myClient;

    String editTextAddress = "10.0.1.50";
    Integer editTextPort = 48;

    boolean keepalive = true;

    ConnectivityManager connManager;





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

        myClient = new Client(editTextAddress, editTextPort, response);


        connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        buttonConnect = (Button) findViewById(R.id.btnconnect);
        buttonClear = (Button) findViewById(R.id.clear);
        response = (TextView) findViewById(R.id.feedback);






        buttonConnect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                    response.setText("");

                    String dat = "Open";

                    try {
                        //String dat = "sec rfdgdf";
                        dat = dat + "\r\n";

                        myClient.sendToPort(dat);


                    } catch (UnknownHostException e) {
                        System.err.println("Trying to connect to unknown host: " + e);
                        response.setText("Trying to connect to unknown host: " + e);
                    } catch (IOException e) {
                        System.err.println("IOException:  " + e);

                    }


            }
        });





    }



    @Override
    public void onResume(){
        super.onResume();

        response.setText("Resum`enter code here`e connected!");



    }
}

You can implement the reconnect logic in the callback of registerNetworkCallback in the ConnectivityManager

The code you provided doesn't use connManager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM