How to connect to pre-configured Wifi in Android?

2019-07-29 04:21发布

So I've been having some trouble figuring this stuff out for myself and I'm rather new at Android so would really appreciate some help on this.

I have taken a look at answers such as these on SO: How do I connect to a specific Wi-Fi network in Android programmatically?

and I see that you have to configure a network, manually put in the password, and add it to the list of configured networks, etc.

I was wondering what one would do in the case of multiple wifi already being configured/saved by the user, and choosing a specific one to connect to programmatically? Does this mean that they already appear in the getConfiguredNetworks() method call? If so, how would one go about executing .enableNetwork(int netId, boolean disableOthers)?

As a side note, both of those functions are part of the WifiManager class. Hopefully this all made sense!

3条回答
We Are One
2楼-- · 2019-07-29 04:55
WifiManager wifiManager = (WifiManager)context.getSystemService(WIFI_SERVICE);              
int netId = -1;         
for (WifiConfiguration tmp : wifiManager.getConfiguredNetworks()) 
   if (tmp.SSID.equals( "\""+"Your SSID"+"\"")) 
   {
      netId = tmp.networkId;                   
      wifiManager.enableNetwork(netId, true);
   }

Just change the string "Your SSID" in the 3rd line to the SSID you want to connect.

And add this permissions in the manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

My first contribution to StackOverflow, hope it helps someone :D

查看更多
Viruses.
3楼-- · 2019-07-29 04:59

wifiManager.enableNetwork(wifiConfiguration.networkId, true);I took the answer by racuevji and elaborated on it. Some more permissions are required and if the wifi is off, the solution below also switches it on:

public class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
                if (!wifiManager.isWifiEnabled())
                {
                    MainActivity.this.registerReceiver(myWifiStateListener,
                                                       new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
                    wifiManager.setWifiEnabled(true);
                }
                connectToSSID(wifiManager, "your_ssid");
            }
        });
    }

    private void connectToSSID(WifiManager wifiManager, String ssid)
    {
        for (WifiConfiguration wifiConfiguration : wifiManager.getConfiguredNetworks())
        {
            if (wifiConfiguration.SSID.equals("\"" + ssid + "\""))
            {
                wifiManager.enableNetwork(wifiConfiguration.networkId, true);
            }
        }
    }

    private BroadcastReceiver myWifiStateListener
            = new BroadcastReceiver()
    {

        @Override
        public void onReceive(Context arg0, Intent arg1)
        {
            NetworkInfo networkInfo = arg1.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI)
            {
                if(networkInfo.getState()== NetworkInfo.State.CONNECTED)
                {
                    connectToSSID((WifiManager) getSystemService(WIFI_SERVICE), "pix4d_office");
                    MainActivity.this.unregisterReceiver(myWifiStateListener);
                }
            }
        }
    };
}

where activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button" android:layout_below="@+id/textView"
        android:layout_toEndOf="@+id/textView" android:layout_marginTop="75dp"/>

</RelativeLayout>

and AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="damsoft.com.wifitest" >
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
查看更多
一纸荒年 Trace。
4楼-- · 2019-07-29 05:14

The main problem with connecting to existing configuration is, that you look for existing network with SSID key, which is not a unique key of the network. You can have at home 2 different networks with the same SSID, or it can happend that network password is changed from the last time, your device was connected to that network. If your app is targeted below 6.0, then you can update saved configuration, if not, then you have a problem and you have to create new WifiConfiguration and save it.

Android Developer on changes in Android 6.0:

Your apps can now change the state of WifiConfiguration objects only if you created these objects. You are not permitted to modify or delete WifiConfiguration objects created by the user or by other apps.

The best scenario that I found it was that I try to connect to every saved network with the same SSID and if every configuration failed to connect, then I have added and saved new Configuration to the device.

查看更多
登录 后发表回答