wait until wifi connected on android

前端 未结 1 1886
借酒劲吻你
借酒劲吻你 2020-12-13 15:01

I have a small program that trying to connect to a wifi network. It enables the wifi on the device then if it\'s the first time that is connect to the certain networkss It l

相关标签:
1条回答
  • 2020-12-13 15:48

    I have found the solution for your problem a month ago, just use Thread put method isConnected() in it.
    In this case, I use WifiExplorerActivity to display all wifi network and allow user connect to it.

            Thread t = new Thread() {
            @Override
            public void run() {
                try {
                        //check if connected!
                    while (!isConnected(WifiExplorerActivity.this)) {
                        //Wait to connect
                        Thread.sleep(1000);                     
                    }
    
                    Intent i = new Intent(WifiExplorerActivity.this, MainActivity.class);
                    startActivity(i);
    
                } catch (Exception e) {
                }
            }
        };
        t.start();
    

    And this is function to check wifi has connected or not:

      public static boolean isConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = null;
        if (connectivityManager != null) {
            networkInfo = connectivityManager.getActiveNetworkInfo();
        }
    
        return networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED;
    }
    

    Finally, make sure your Androidmanifest.xml look like this:

        <activity android:name=".WifiExplorerActivity" >        
        <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
    </activity>
    

    Also, you can use ProgressDialog to wait connect. See http://developer.android.com/guide/topics/ui/dialogs.html

    0 讨论(0)
提交回复
热议问题