簡體   English   中英

如何在Android中建立一致的WIFI連接

[英]How to make a consistent WIFI connection in android

在我的新android應用中,我已直接通過TCP連接到具有特定IP和端口的設備,並且一切正常。 這里的問題是,當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!");



    }
}

您可以在ConnectivityManagerregisterNetworkCallback回調中實現重新連接邏輯

您提供的代碼不使用connManager

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM