如何以编程方式在android中创建一个开放的Wifi网络?

时间:2014-07-31 18:57:17

标签: android android-wifi

我想以编程方式在Android中创建开放式网络。我使用以下代码:

WifiManager mainWifiObj;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainWifiObj = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    addNetwork();
}
//Add Dummy Wifi     
public void addNetwork(){
    WifiConfiguration wc = new WifiConfiguration();
    wc.SSID = dummyTemp;
    wc.status = WifiConfiguration.Status.ENABLED;
    wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    //Get Network ID from the MainWiFi Object
    dummyNetworkId = mainWifiObj.addNetwork(wc);
    //Success, can call mainWifiObj.enableNetwork(networkId, false)
    if (dummyNetworkId != -1) {   mainWifiObj.enableNetwork(wc.networkId, false); }
}

然而,当我进入Wifi菜单时,我没有看到添加此网络。请帮忙。

编辑:

我拥有必要的权限。我可以查看其他网络,我只是无法添加其他网络。这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.pervysage.wifi" >

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


    <application
        android:allowBackup="true"
        android:icon="@drawable/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>

2 个答案:

答案 0 :(得分:1)

所以,奇怪的怪癖,你必须将SSID包装在引号中才能工作:

wc.SSID = dummyTemp;

应该是:

wc.SSID = "\"" + dummyTemp + "\"";

编辑:从WifiConfiguration类添加了Javadoc:

/**
 * The network's SSID. Can either be an ASCII string,
 * which must be enclosed in double quotation marks
 * (e.g., {@code "MyNetwork"}, or a string of
 * hex digits,which are not enclosed in quotes
 * (e.g., {@code 01a243f405}).
 */
public String SSID;

答案 1 :(得分:0)

您需要在清单文件中拥有以下权限:

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

然后,您可以在活动类中使用以下内容:

WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

使用以下内容检查是否已启用

boolean wifiEnabled = wifiManager.isWifiEnabled()

您可以在this网站上找到关于该主题的精彩教程。