wifi扫描及连接

本文介绍了如何在Android中进行WiFi扫描和连接的操作。提供了一个主界面搜索附近WiFi的示例,以及相关工具类和布局文件。此外,还分享了GitHub上的DEMO下载链接和相关Android WiFi操作的教程链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文实例讲述了Android编程实现wifi扫描及连接的方法。分享给大家供大家参考,具体如下:

主界面,搜索附近WIFI信息

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

/**

 * Search WIFI and show in ListView

 *

 */

public class MainActivity extends Activity implements OnClickListener,

    OnItemClickListener {

  private Button search_btn;

  private ListView wifi_lv;

  private WifiUtils mUtils;

  private List<String> result;

  private ProgressDialog progressdlg = null;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mUtils = new WifiUtils(this);

    findViews();

    setLiteners();

  }

  private void findViews() {

    this.search_btn = (Button) findViewById(R.id.search_btn);

    this.wifi_lv = (ListView) findViewById(R.id.wifi_lv);

  }

  private void setLiteners() {

    search_btn.setOnClickListener(this);

    wifi_lv.setOnItemClickListener(this);

  }

  @Override

  public void onClick(View v) {

    if (v.getId() == R.id.search_btn) {

      showDialog();

      new MyAsyncTask().execute();

    }

  }

  /**

   * init dialog and show

   */

  private void showDialog() {

    progressdlg = new ProgressDialog(this);

    progressdlg.setCanceledOnTouchOutside(false);

    progressdlg.setCancelable(false);

    progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    progressdlg.setMessage(getString(R.string.wait_moment));

    progressdlg.show();

  }

  /**

   * dismiss dialog

   */

  private void progressDismiss() {

    if (progressdlg != null) {

      progressdlg.dismiss();

    }

  }

  class MyAsyncTask extends AsyncTask<Void, Void, Void> {

    @Override

    protected Void doInBackground(Void... arg0) {

      //扫描附近WIFI信息

      result = mUtils.getScanWifiResult();

      return null;

    }

    @Override

    protected void onPostExecute(Void result) {

      super.onPostExecute(result);

      progressDismiss();

      initListViewData();

    }

  }

  private void initListViewData() {

    if (null != result && result.size() > 0) {

      wifi_lv.setAdapter(new ArrayAdapter<String>(

          getApplicationContext(), R.layout.wifi_list_item,

          R.id.ssid, result));

    } else {

      wifi_lv.setEmptyView(findViewById(R.layout.list_empty));

    }

  }

  @Override

  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    TextView tv = (TextView) arg1.findViewById(R.id.ssid);

    if (!TextUtils.isEmpty(tv.getText().toString())) {

      Intent in = new Intent(MainActivity.this, WifiConnectActivity.class);

      in.putExtra("ssid", tv.getText().toString());

      startActivity(in);

    }

  }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

/**

 * 连接指定的WIFI

 *

 */

public class WifiConnectActivity extends Activity implements OnClickListener {

  private Button connect_btn;

  private TextView wifi_ssid_tv;

  private EditText wifi_pwd_tv;

  private WifiUtils mUtils;

  // wifi之ssid

  private String ssid;

  private String pwd;

  private ProgressDialog progressdlg = null;

  @SuppressLint("HandlerLeak")

  private Handler mHandler = new Handler() {

    public void handleMessage(android.os.Message msg) {

      switch (msg.what) {

      case 0:

        showToast("WIFI连接成功");

        finish();

        break;

      case 1:

        showToast("WIFI连接失败");

        break;

      }

      progressDismiss();

    }

  };

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_connect);

    mUtils = new WifiUtils(this);

    findViews();

    setLiteners();

    initDatas();

  }

  /**

   * init dialog

   */

  private void progressDialog() {

    progressdlg = new ProgressDialog(this);

    progressdlg.setCanceledOnTouchOutside(false);

    progressdlg.setCancelable(false);

    progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);

    progressdlg.setMessage(getString(R.string.wait_moment));

    progressdlg.show();

  }

  /**

   * dissmiss dialog

   */

  private void progressDismiss() {

    if (progressdlg != null) {

      progressdlg.dismiss();

    }

  }

  private void initDatas() {

    ssid = getIntent().getStringExtra("ssid");

    if (!TextUtils.isEmpty(ssid)) {

      ssid = ssid.replace("\"", "");

    }

    this.wifi_ssid_tv.setText(ssid);

  }

  private void findViews() {

    this.connect_btn = (Button) findViewById(R.id.connect_btn);

    this.wifi_ssid_tv = (TextView) findViewById(R.id.wifi_ssid_tv);

    this.wifi_pwd_tv = (EditText) findViewById(R.id.wifi_pwd_tv);

  }

  private void setLiteners() {

    connect_btn.setOnClickListener(this);

  }

  @Override

  public void onClick(View v) {

    if (v.getId() == R.id.connect_btn) {// 下一步操作

      pwd = wifi_pwd_tv.getText().toString();

      // 判断密码输入情况

      if (TextUtils.isEmpty(pwd)) {

        Toast.makeText(this, "请输入wifi密码", Toast.LENGTH_SHORT).show();

        return;

      }

      progressDialog();

      // 在子线程中处理各种业务

      dealWithConnect(ssid, pwd);

    }

  }

  private void dealWithConnect(final String ssid, final String pwd) {

    new Thread(new Runnable() {

      @Override

      public void run() {

        Looper.prepare();

        // 检验密码输入是否正确

        boolean pwdSucess = mUtils.connectWifiTest(ssid, pwd);

        try {

          Thread.sleep(4000);

        } catch (Exception e) {

          e.printStackTrace();

        }

        if (pwdSucess) {

          mHandler.sendEmptyMessage(0);

        } else {

          mHandler.sendEmptyMessage(1);

        }

      }

    }).start();

  }

  private void showToast(String str) {

    Toast.makeText(WifiConnectActivity.this, str, Toast.LENGTH_SHORT).show();

  }

}

工具类:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

public class WifiUtils {

  // 上下文Context对象

  private Context mContext;

  // WifiManager对象

  private WifiManager mWifiManager;

  public WifiUtils(Context mContext) {

    this.mContext = mContext;

    mWifiManager = (WifiManager) mContext

        .getSystemService(Context.WIFI_SERVICE);

  }

  /**

   * 判断手机是否连接在Wifi上

   */

  public boolean isConnectWifi() {

    // 获取ConnectivityManager对象

    ConnectivityManager conMgr = (ConnectivityManager) mContext

        .getSystemService(Context.CONNECTIVITY_SERVICE);

    // 获取NetworkInfo对象

    NetworkInfo info = conMgr.getActiveNetworkInfo();

    // 获取连接的方式为wifi

    State wifi = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI)

        .getState();

    if (info != null && info.isAvailable() && wifi == State.CONNECTED)

    {

      return true;

    } else {

      return false;

    }

  }

  /**

   * 获取当前手机所连接的wifi信息

   */

  public WifiInfo getCurrentWifiInfo() {

    return mWifiManager.getConnectionInfo();

  }

  /**

   * 添加一个网络并连接 传入参数:WIFI发生配置类WifiConfiguration

   */

  public boolean addNetwork(WifiConfiguration wcg) {

    int wcgID = mWifiManager.addNetwork(wcg);

    return mWifiManager.enableNetwork(wcgID, true);

  }

  /**

   * 搜索附近的热点信息,并返回所有热点为信息的SSID集合数据

   */

  public List<String> getScanWifiResult() {

    // 扫描的热点数据

    List<ScanResult> resultList;

    // 开始扫描热点

    mWifiManager.startScan();

    resultList = mWifiManager.getScanResults();

    ArrayList<String> ssids = new ArrayList<String>();

    if (resultList != null) {

      for (ScanResult scan : resultList) {

        ssids.add(scan.SSID);// 遍历数据,取得ssid数据集

      }

    }

    return ssids;

  }

  /**

   * 连接wifi 参数:wifi的ssid及wifi的密码

   */

  public boolean connectWifiTest(final String ssid, final String pwd) {

    boolean isSuccess = false;

    boolean flag = false;

    mWifiManager.disconnect();

    boolean addSucess = addNetwork(CreateWifiInfo(ssid, pwd, 3));

    if (addSucess) {

      while (!flag && !isSuccess) {

        try {

          Thread.sleep(10000);

        } catch (InterruptedException e1) {

          e1.printStackTrace();

        }

        String currSSID = getCurrentWifiInfo().getSSID();

        if (currSSID != null)

          currSSID = currSSID.replace("\"", "");

        int currIp = getCurrentWifiInfo().getIpAddress();

        if (currSSID != null && currSSID.equals(ssid) && currIp != 0) {

          isSuccess = true;

        } else {

          flag = true;

        }

      }

    }

    return isSuccess;

  }

  /**

   * 创建WifiConfiguration对象 分为三种情况:1没有密码;2用wep加密;3用wpa加密

   *

   * @param SSID

   * @param Password

   * @param Type

   * @return

   */

  public WifiConfiguration CreateWifiInfo(String SSID, String Password,

      int Type) {

    WifiConfiguration config = new WifiConfiguration();

    config.allowedAuthAlgorithms.clear();

    config.allowedGroupCiphers.clear();

    config.allowedKeyManagement.clear();

    config.allowedPairwiseCiphers.clear();

    config.allowedProtocols.clear();

    config.SSID = "\"" + SSID + "\"";

    WifiConfiguration tempConfig = this.IsExsits(SSID);

    if (tempConfig != null) {

      mWifiManager.removeNetwork(tempConfig.networkId);

    }

    if (Type == 1) // WIFICIPHER_NOPASS

    {

      config.wepKeys[0] = "";

      config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

      config.wepTxKeyIndex = 0;

    }

    if (Type == 2) // WIFICIPHER_WEP

    {

      config.hiddenSSID = true;

      config.wepKeys[0] = "\"" + Password + "\"";

      config.allowedAuthAlgorithms

          .set(WifiConfiguration.AuthAlgorithm.SHARED);

      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);

      config.allowedGroupCiphers

          .set(WifiConfiguration.GroupCipher.WEP104);

      config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

      config.wepTxKeyIndex = 0;

    }

    if (Type == 3) // WIFICIPHER_WPA

    {

      config.preSharedKey = "\"" + Password + "\"";

      config.hiddenSSID = true;

      config.allowedAuthAlgorithms

          .set(WifiConfiguration.AuthAlgorithm.OPEN);

      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

      config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);

      config.allowedPairwiseCiphers

          .set(WifiConfiguration.PairwiseCipher.TKIP);

      // config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);

      config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);

      config.allowedPairwiseCiphers

          .set(WifiConfiguration.PairwiseCipher.CCMP);

      config.status = WifiConfiguration.Status.ENABLED;

    }

    return config;

  }

  private WifiConfiguration IsExsits(String SSID) {

    List<WifiConfiguration> existingConfigs = mWifiManager

        .getConfiguredNetworks();

    for (WifiConfiguration existingConfig : existingConfigs) {

      if (existingConfig.SSID.equals("\"" + SSID + "\"")) {

        return existingConfig;

      }

    }

    return null;

  }

}

—–相关布局文件————–

主页面

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<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" >

  <Button

    android:id="@+id/search_btn"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_margin="10dp"

    android:text="搜索附近WIFI"

    android:textSize="16sp" >

  </Button>

  <ListView

    android:id="@+id/wifi_lv"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_below="@id/search_btn"

    android:layout_marginTop="10dp"

    android:divider="#d1d1d1"

    android:dividerHeight="1px"

    android:scrollbars="none" >

  </ListView>

</RelativeLayout>

连接页面

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<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" >

  <TextView

    android:id="@+id/wifi_ssid"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginTop="15dp"

    android:padding="10dp"

    android:text="@string/wifi_ssid"

    android:textSize="16sp" />

  <TextView

    android:id="@+id/wifi_ssid_tv"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_marginTop="15dp"

    android:layout_toRightOf="@id/wifi_ssid"

    android:padding="10dp"

    android:textSize="16sp" />

  <TextView

    android:id="@+id/wifi_pwd"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_below="@id/wifi_ssid"

    android:layout_marginTop="15dp"

    android:padding="10dp"

    android:text="@string/wifi_pwd"

    android:textSize="16sp" />

  <EditText

    android:id="@+id/wifi_pwd_tv"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_below="@id/wifi_ssid_tv"

    android:layout_marginRight="15dp"

    android:layout_marginTop="15dp"

    android:layout_toRightOf="@id/wifi_pwd"

    android:hint="@string/input_pwd_hint"

    android:padding="10dp"

    android:textSize="16sp" />

  <Button

    android:id="@+id/connect_btn"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_alignParentBottom="true"

    android:layout_margin="10dp"

    android:text="连接WIFI"

    android:textSize="16sp" >

  </Button>

</RelativeLayout>

主页面ListView的item

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<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="40dp"

  android:background="#FFFFFF" >

  <TextView

    android:id="@+id/ssid"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_alignParentLeft="true"

    android:layout_centerInParent="true"

    android:paddingLeft="15dp"

    android:textColor="#333333"

    android:textSize="16sp" />

</RelativeLayout>

主界面未搜索 到WIFI的展示

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<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:background="#FFFFFF" >

  <TextView

    android:id="@+id/ssid"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_centerInParent="true"

    android:text="附近暂时没有WIFI"

    android:textColor="#333333"

    android:textSize="16sp" />

</RelativeLayout>

github上DEMO下载地址:https://github.com/ldm520/WIFI_TOOL

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android硬件相关操作与应用总结》、《Android资源操作技巧汇总》、《Android视图View技巧总结》、《Android开发入门与进阶教程》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:

原文链接:http://blog.csdn.net/true100/article/details/50915993

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值