Java 如何在android中连接wifi

Java 如何在android中连接wifi,java,android,Java,Android,我是android应用程序开发的新手,目前我编写了android Wifi连接代码以实现连接。该应用程序显示了可用的连接,但我无法连接到特定的Wifi连接 下面是我从搜索中获得的一个连接,我可以在我的大学校舍中看到很多此类连接 例如:能力[WPA2-PSK CCMP][WPS][ESS],级别:-37,自由度2412时间戳:9103895476 您能帮我解决这个问题并正确连接到可用的连接吗。此外,我已决定实施Wifi开/关按钮,对此实施没有明确的想法 下面是我的Java代码 TextView m

我是android应用程序开发的新手,目前我编写了android Wifi连接代码以实现连接。该应用程序显示了可用的连接,但我无法连接到特定的Wifi连接

下面是我从搜索中获得的一个连接,我可以在我的大学校舍中看到很多此类连接

例如:能力[WPA2-PSK CCMP][WPS][ESS],级别:-37,自由度2412时间戳:9103895476

您能帮我解决这个问题并正确连接到可用的连接吗。此外,我已决定实施Wifi开/关按钮,对此实施没有明确的想法

下面是我的Java代码

TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();

public void onCreate(Bundle savedInstanceState) {

   super.onCreate(savedInstanceState);

   setContentView(R.layout.activity_wifi_connections);
   mainText = (TextView) findViewById(R.id.mainText);

   // Initiate wifi service manager
   mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

   // Check for wifi is disabled
   if (mainWifi.isWifiEnabled() == false)
        {   
            // If wifi disabled then enable it
            Toast.makeText(getApplicationContext(), "wifi is disabled..making it enabled", Toast.LENGTH_LONG).show();
            mainWifi.setWifiEnabled(true);
        } 

   // wifi scaned value broadcast receiver 
   receiverWifi = new WifiReceiver();

   // Register broadcast receiver 
   // Broacast receiver will automatically call when number of wifi connections changed
   registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
   mainWifi.startScan();
   mainText.setText("Starting Scan...");
}

public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(0, 0, 0, "Refresh");
    return super.onCreateOptionsMenu(menu);
}

public boolean onMenuItemSelected(int featureId, MenuItem item) {
    mainWifi.startScan();
    mainText.setText("Starting Scan");
    return super.onMenuItemSelected(featureId, item);
}

protected void onPause() {
    unregisterReceiver(receiverWifi);
    super.onPause();
}

protected void onResume() {
    registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    super.onResume();
}

// Broadcast receiver class called its receive method 
// when number of wifi connections changed

class WifiReceiver extends BroadcastReceiver {

    // This method call when number of wifi connections changed
    public void onReceive(Context c, Intent intent) {

        sb = new StringBuilder();
        wifiList = mainWifi.getScanResults(); 
        sb.append("\n        Number Of Wifi connections :"+wifiList.size()+"\n\n");

        for(int i = 0; i < wifiList.size(); i++){

            sb.append(new Integer(i+1).toString() + ". ");
            sb.append((wifiList.get(i)).toString());
            sb.append("\n\n");
        }

        mainText.setText(sb);  
    }

}
text查看主文本;
WifiManager mainWifi;
无线接收器接收器;
列表wifiList;
StringBuilder sb=新的StringBuilder();
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u wifi\u连接);
mainText=(TextView)findViewById(R.id.mainText);
//启动wifi服务管理器
mainWifi=(WifiManager)getSystemService(Context.WIFI\u SERVICE);
//检查wifi是否已禁用
if(mainWifi.isWifiEnabled()==false)
{   
//如果禁用wifi,则启用它
Toast.makeText(getApplicationContext(),“wifi已禁用..正在启用”,Toast.LENGTH_LONG.show();
mainWifi.setWifiEnabled(true);
} 
//无线扫描值广播接收机
receiverWifi=新WifiReceiver();
//寄存器广播接收机
//Broacast接收器将在wifi连接数更改时自动呼叫
registerReceiver(接收方WiFi,新的意向过滤器(WifiManager.SCAN\u RESULTS\u AVAILABLE\u ACTION));
mainWifi.startScan();
setText(“开始扫描…”);
}
公共布尔onCreateOptions菜单(菜单){
添加(0,0,0,“刷新”);
返回super.onCreateOptions菜单(菜单);
}
公共布尔值onMenuItemSelected(int-featureId,MenuItem项){
mainWifi.startScan();
setText(“开始扫描”);
返回super.onMenuItemSelected(featureId,item);
}
受保护的void onPause(){
未注册的接收器(接收器);
super.onPause();
}
受保护的void onResume(){
registerReceiver(接收方WiFi,新的意向过滤器(WifiManager.SCAN\u RESULTS\u AVAILABLE\u ACTION));
super.onResume();
}
//广播接收器类调用其接收方法
//当wifi连接数发生变化时
类WifiReceiver扩展了BroadcastReceiver{
//此方法在wifi连接数更改时调用
接收时公共无效(上下文c,意图){
sb=新的StringBuilder();
wifiList=mainWifi.getScanResults();
sb.追加(“\n Wifi连接数:”+wifiList.size()+“\n\n”);
对于(int i=0;i
下面是我的清单代码

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.androidexample.wificonnections.WifiConnections"
        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>

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


第一步是确定接入点的加密类型。为此,您可以参考

以下是可用于检查特定SSID加密类型的代码:

public String getEncryptionType(String ssid){

    String encryptType = "";
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    List<ScanResult> networkList = wifi.getScanResults();

    if (networkList != null) {
        for (ScanResult network : networkList)
        {
            //check if current connected SSID
            if (ssid.equals(network.SSID)){
                //get capabilities of current connection
                String Capabilities =  network.capabilities;
                Log.d (TAG, network.SSID + " capabilities : " + Capabilities);

                if (Capabilities.contains("WPA2")) {
                    encryptType = "WPA2";
                }
                else if (Capabilities.contains("WPA")) {
                    encryptType = "WPA";
                }
                else if (Capabilities.contains("WEP")) {
                    encryptType = "WEP";
                }
            }
        }

    }
    return encryptType;
}   

根据文档,当您调用“mWifiManager.enableNetwork(config.networkId,true);”时,最后一个参数('true')指示操作系统禁用所有其他网络,因此无需单独禁用每个网络。
public boolean ConnectToNetworkWEP( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes
        conf.wepKeys[0] = "\"" + password + "\""; //Try it with quotes first

        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.OPEN);
        conf.allowedGroupCiphers.set(WifiConfiguration.AuthAlgorithm.SHARED);


        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        int networkId = wifiManager.addNetwork(conf);

        if (networkId == -1){
            //Try it again with no quotes in case of hex password
            conf.wepKeys[0] = password;
            networkId = wifiManager.addNetwork(conf);
        }

        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                break;
            }
        }

        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}
public boolean ConnectToNetworkWPA( String networkSSID, String password )
{
    try {
        WifiConfiguration conf = new WifiConfiguration();
        conf.SSID = "\"" + networkSSID + "\"";   // Please note the quotes. String should contain SSID in quotes

        conf.preSharedKey = "\"" + password + "\"";

        conf.status = WifiConfiguration.Status.ENABLED;
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);

        Log.d("connecting", conf.SSID + " " + conf.preSharedKey);

        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.addNetwork(conf);

        Log.d("after connecting", conf.SSID + " " + conf.preSharedKey);



        List<WifiConfiguration> list = wifiManager.getConfiguredNetworks();
        for( WifiConfiguration i : list ) {
            if(i.SSID != null && i.SSID.equals("\"" + networkSSID + "\"")) {
                wifiManager.disconnect();
                wifiManager.enableNetwork(i.networkId, true);
                wifiManager.reconnect();
                Log.d("re connecting", i.SSID + " " + conf.preSharedKey);

                break;
            }
        }


        //WiFi Connection success, return true
        return true;
    } catch (Exception ex) {
        System.out.println(Arrays.toString(ex.getStackTrace()));
        return false;
    }
}
public void connectToNetwork(String ssid){

    WifiInfo info = mWifiManager.getConnectionInfo(); //get WifiInfo
    int id = info.getNetworkId(); //get id of currently connected network

    for (WifiConfiguration config : configurations) {
        // If it was cached connect to it and that's all
        if (config.SSID != null && config.SSID.equals("\"" +ssid + "\"")) {
            // Log
            Log.i("connectToNetwork", "Connecting to: " + config.SSID);

            mWifiManager.disconnect();

            mWifiManager.disableNetwork(id); //disable current network

            mWifiManager.enableNetwork(config.networkId, true);
            mWifiManager.reconnect();
            break;
        }
    }
}