Android:如何通过代码启动WiFi

时间:2012-04-20 06:30:53

标签: android android-wifi onitemclick

我想创建一个检测wifi网络的简单应用程序,在选择网络后,它会启动(连接)到所选网络。

我已经为检测阶段编写了代码但是如何在onItemClick()中连接到所选网络。 请建议代码。

3 个答案:

答案 0 :(得分:6)

您可以使用WifiManager执行此操作。从系统获取Wifi服务,检查wifi是打开还是关闭,然后打开/关闭。

private WifiManager wifiManager;
@Override
public void onCreate(Bundle bund) {
  wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
  if(wifiManager.isWifiEnabled()){
    wifiManager.setWifiEnabled(false);
  }else{
    wifiManager.setWifiEnabled(true);
  }
}

请记住也要添加权限

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

答案 1 :(得分:3)

Android完全支持WiFi连接。主要组件是系统提供的WiFiManager。像往常一样,我们通过getSystemServices()调用当前上下文来获取它。

一旦我们拥有WiFiManager,我们可以以WiFiInfo对象的形式询问它当前的WIFi连接。我们还可以通过getConfiguredNetworks()请求所有当前可用的网络。这给了我们WifiConfigurations的列表。

在这个例子中,我们还注册了一个广播接收器来执行新网络的扫描

<强> WiFiDemo.java

package com.example;

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class WiFiDemo extends Activity implements OnClickListener {
    private static final String TAG = "WiFiDemo";
    WifiManager wifi;
    BroadcastReceiver receiver;

    TextView textStatus;
    Button buttonScan;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Setup UI
        textStatus = (TextView) findViewById(R.id.textStatus);
        buttonScan = (Button) findViewById(R.id.buttonScan);
        buttonScan.setOnClickListener(this);

        // Setup WiFi
        wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

        // Get WiFi status
        WifiInfo info = wifi.getConnectionInfo();
        textStatus.append("\n\nWiFi Status: " + info.toString());

        // List available networks
        List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
        for (WifiConfiguration config : configs) {
            textStatus.append("\n\n" + config.toString());
        }

        // Register Broadcast Receiver
        if (receiver == null)
            receiver = new WiFiScanReceiver(this);

        registerReceiver(receiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        Log.d(TAG, "onCreate()");
    }

    @Override
    public void onStop() {
        unregisterReceiver(receiver);
    }

    public void onClick(View view) {
        Toast.makeText(this, "On Click Clicked. Toast to that!!!",
                Toast.LENGTH_LONG).show();

        if (view.getId() == R.id.buttonScan) {
            Log.d(TAG, "onClick() wifi.startScan()");
            wifi.startScan();
        }
    }

}

<强> WiFiScanReceiver.java

package com.example;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.widget.Toast;

public class WiFiScanReceiver extends BroadcastReceiver {
  private static final String TAG = "WiFiScanReceiver";
  WiFiDemo wifiDemo;

  public WiFiScanReceiver(WiFiDemo wifiDemo) {
    super();
    this.wifiDemo = wifiDemo;
  }

  @Override
  public void onReceive(Context c, Intent intent) {
    List<ScanResult> results = wifiDemo.wifi.getScanResults();
    ScanResult bestSignal = null;
    for (ScanResult result : results) {
      if (bestSignal == null
          || WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
        bestSignal = result;
    }

    String message = String.format("%s networks found. %s is the strongest.",
        results.size(), bestSignal.SSID);
    Toast.makeText(wifiDemo, message, Toast.LENGTH_LONG).show();

    Log.d(TAG, "onReceive() message: " + message);
  }

}

此示例的布局文件非常简单。它有一个TextView包装在ScrollView中以便滚动。

<强> /res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical" android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <Button android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:id="@+id/buttonScan"
    android:text="Scan"></Button>
  <ScrollView android:id="@+id/ScrollView01"
    android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content" android:id="@+id/textStatus"
      android:text="WiFiDemo" />
  </ScrollView>

</LinearLayout>

对于 AndroidManifest.xml 文件,只需记住添加使用WiFi的权限:

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

答案 2 :(得分:0)

也许您可以使用现有的Answer's

WifiConfigurations将帮助您完成此操作。

希望这会对你有所帮助。