如何以编程方式连接到WiFi

时间:2015-04-11 06:09:33

标签: android android-wifi

我正在尝试使用应用程序而不是使用以下代码的android wifi设置连接到新的wifi网络,但似乎相关的android sdk类只允许您连接到已存储在android中的网络而不是任何新网络。我认为这是正确的吗?

这是我的代码

表现XML:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="unitedspark.testapp" >
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".WiFiConnect"
        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>
<receiver android:name=".WiFiChangeReciever" >
    <intent-filter>
        <action android:name="android.net.wifi.STATE_CHANGE" />
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
</manifest>

活动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=".WiFiConnect"
android:id="@+id/WiFiConnectLayout">

<TextView
    android:id="@+id/Connect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Connect To"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_marginTop="63dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New WiFi Network"
    android:id="@+id/btnConnectNetwork1"
    android:layout_alignTop="@+id/btnDisconnect"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Disconnect"
    android:id="@+id/btnDisconnect"
    android:layout_marginTop="108dp"
    android:layout_below="@+id/btnConnectNetwork1"
    android:layout_toRightOf="@+id/btnConnectNetwork1"
    android:layout_toEndOf="@+id/btnConnectNetwork1" />

<TextView
    android:id="@+id/txtStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="WiFi Status"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:layout_marginTop="67dp"
    android:layout_below="@+id/btnDisconnect"
    android:layout_centerHorizontal="true" />

java文件:

package unitedspark.testapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Arrays;
import java.util.List;


public class WiFiConnect extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wi_fi_connect);

    this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

    Button btnConnectNetwork1 = (Button) findViewById(R.id.btnConnectNetwork1);
    btnConnectNetwork1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            TextView txtStatus = (TextView)findViewById(R.id.txtStatus);

            WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            if(!wifi.isWifiEnabled()) {
                wifi.setWifiEnabled(true);
            }

            txtStatus.setText("Trying to connect...");

            ConnectToNetworkWEP("SSID1", "Password1");
        }
    });

    Button btnDisconnect = (Button) findViewById(R.id.btnDisconnect);
    btnDisconnect.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            TextView txtStatus = (TextView)findViewById(R.id.txtStatus);
            txtStatus.setText("Trying to disconnect...");

            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wifiManager.disconnect();
            wifiManager.setWifiEnabled(false);
            txtStatus.setText("Disconnected!");
        }
    });


}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {

        NetworkInfo currentNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        if (currentNetworkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();

            Toast.makeText(getApplicationContext(), "Broadcast Connected:" +  wifiInfo.getSSID(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Broadcast Not Connected", Toast.LENGTH_LONG).show();
        }
    }
};


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_wi_fi_connect, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

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;  //WEP password is in hex, we do not need to surround it with quotes.
        conf.wepTxKeyIndex = 0;
        conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
        conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

        WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        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;
    }
}
}

1 个答案:

答案 0 :(得分:2)

我刚用家庭WiFi网络进行WPA2身份验证。

您的断开连接代码可以正常工作。我能够通过按钮重复连接和断开连接。

对于您的WEP网络,请尝试以下方法:

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;
    }
}

这是在WPA2上为我工作的代码:

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;
        }
    }