如何在android中建立一致的WIFI连接

时间:2017-01-15 21:15:23

标签: java android

在我的新Android应用程序中,我已经与具有特定IP和端口的设备建立了直接tcp连接,一切正常。这里的问题是当Wifi断开连接时它不会重新连接或再次发送数据。

在我的代码中,我有一个课程Client.javaMainActivity.java以下。

我该怎么做?

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

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!");



    }
}

1 个答案:

答案 0 :(得分:0)

您可以在registerNetworkCallback in the ConnectivityManager

的回调中实现重新连接逻辑

您提供的代码不使用connManager