android wifi连接开发实例

android-wifi 专栏收录该内容
8 篇文章 0 订阅

转自:http://blog.csdn.net/dianqiugg/article/details/8205613

参考网上代码,结合了自己的想法,废话不多说,直接上代码

1、布局文件:wifi_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="match_parent"
 android:layout_height="match_parent">
 <Button android:id="@+id/scan_button" android:layout_width="fill_parent"
  android:layout_height="wrap_content" android:text="扫描"
  android:textColor="#000000" />
 <TextView android:id="@+id/wifi_result_textview"
  android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>
2、Activity:WifiActivity.java

/**
 * @Title: WifiActivity.java
 * @Package com.ly
 * @Description:
 * Copyright: Copyright (c) 2011
 * 
 * @date 2012-11-9 上午11:47:51
 * @version V1.0
 */

package com.android.activity;

import java.util.List;

import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.demo.R;
import com.android.util.WifiUtil;

/**
 * @ClassName: WifiActivity
 * @Description: TODO
 * @date 2012-11-9 上午11:47:51
 *
 */
public class WifiActivity extends BaseActivity implements OnClickListener
{

 private Button scan_button;

 private TextView wifi_result_textview;

 private WifiManager wifiManager;

 private WifiInfo currentWifiInfo;// 当前所连接的wifi

 private List<ScanResult> wifiList;// wifi列表

 private String[] str;

 private int wifiIndex;

 private ProgressDialog progressDialog;

 @Override
 protected void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.wifi_layout);
  wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  setupViews();
  initListener();
 }

 @Override
 protected void onResume()
 {
  openWifi();
  currentWifiInfo = wifiManager.getConnectionInfo();
  wifi_result_textview.setText("当前网络:" + currentWifiInfo.getSSID()
    + " ip:" + WifiUtil.intToIp(currentWifiInfo.getIpAddress()));
  new ScanWifiThread().start();
  super.onResume();
 }

 @Override
 public void setupViews()
 {
  scan_button = (Button) findViewById(R.id.scan_button);
  wifi_result_textview = (TextView) findViewById(R.id.wifi_result_textview);
  super.setupViews();
 }

 @Override
 public void initListener()
 {
  scan_button.setOnClickListener(this);
  super.initListener();
 }

 @Override
 public void onClick(View v)
 {
  switch (v.getId())
  {
  case R.id.scan_button:
   lookUpScan();
   break;
  }
 }

 /**
  * 打开wifi
  */
 public void openWifi()
 {
  if (!wifiManager.isWifiEnabled())
  {
   wifiManager.setWifiEnabled(true);
  }
 }

 /**
  * 扫描wifi线程
  *
  * @author passing
  *
  */
 class ScanWifiThread extends Thread
 {

  @Override
  public void run()
  {
   while (true)
   {
    currentWifiInfo = wifiManager.getConnectionInfo();
    startScan();
    try
    {
     Thread.sleep(1000);
    }
    catch (InterruptedException e)
    {
     break;
    }
   }
  }
 }

 /**
  * 扫描wifi
  */
 public void startScan()
 {
  wifiManager.startScan();
  // 获取扫描结果
  wifiList = wifiManager.getScanResults();
  str = new String[wifiList.size()];
  String tempStr = null;
  for (int i = 0; i < wifiList.size(); i++)
  {
   tempStr = wifiList.get(i).SSID;
   if (null != currentWifiInfo
     && tempStr.equals(currentWifiInfo.getSSID()))
   {
    tempStr = tempStr + "(已连接)";
   }
   str[i] = tempStr;
  }
 }

 /**
  * 弹出框 查看扫描结果
  */
 public void lookUpScan()
 {
  Builder builder = new Builder(WifiActivity.this);
  builder.setTitle("wifi");
  builder.setItems(str, new DialogInterface.OnClickListener()
  {

   @Override
   public void onClick(DialogInterface dialog, int which)
   {
    wifiIndex = which;
    handler.sendEmptyMessage(3);
   }
  });
  builder.show();
 }

 /**
  * 获取网络ip地址
  *
  * @author passing
  *
  */
 class RefreshSsidThread extends Thread
 {

  @Override
  public void run()
  {
   boolean flag = true;
   while (flag)
   {
    currentWifiInfo = wifiManager.getConnectionInfo();
    if (null != currentWifiInfo.getSSID()
      && 0 != currentWifiInfo.getIpAddress())
    {
     flag = false;
    }
   }
   handler.sendEmptyMessage(4);
   super.run();
  }
 }

 /**
  * 连接网络
  *
  * @param index
  * @param password
  */
 public void connetionConfiguration(int index, String password)
 {
  progressDialog = ProgressDialog.show(WifiActivity.this, "正在连接...",
    "请稍候...");
  new ConnectWifiThread().execute(index + "", password);
 }

 /**
  * 连接wifi
  *
  * @author passing
  *
  */
 class ConnectWifiThread extends AsyncTask<String, Integer, String>
 {

  @Override
  protected String doInBackground(String... params)
  {
   int index = Integer.parseInt(params[0]);
   if (index > wifiList.size())
   {
    return null;
   }
   // 连接配置好指定ID的网络
   WifiConfiguration config = WifiUtil.createWifiInfo(
     wifiList.get(index).SSID, params[1], 3, wifiManager);

   int networkId = wifiManager.addNetwork(config);
   if (null != config)
   {
    wifiManager.enableNetwork(networkId, true);
    return wifiList.get(index).SSID;
   }
   return null;
  }

  @Override
  protected void onPostExecute(String result)
  {
   if (null != progressDialog)
   {
    progressDialog.dismiss();
   }
   if (null != result)
   {
    handler.sendEmptyMessage(0);
   }
   else
   {
    handler.sendEmptyMessage(1);
   }
   super.onPostExecute(result);
  }

 }

 Handler handler = new Handler()
 {

  @Override
  public void handleMessage(Message msg)
  {
   switch (msg.what)
   {
   case 0:
    wifi_result_textview.setText("正在获取ip地址...");
    new RefreshSsidThread().start();
    break;
   case 1:
    Toast.makeText(WifiActivity.this, "连接失败!", Toast.LENGTH_SHORT)
      .show();
    break;
   case 3:
    View layout = LayoutInflater.from(WifiActivity.this).inflate(
      R.layout.custom_dialog_layout, null);
    Builder builder = new Builder(WifiActivity.this);
    builder.setTitle("请输入密码").setView(layout);
    final EditText passowrdText = (EditText) layout
      .findViewById(R.id.password_edittext);
    builder.setPositiveButton("连接",
      new DialogInterface.OnClickListener()
      {

       @Override
       public void onClick(DialogInterface dialog,
         int which)
       {
        connetionConfiguration(wifiIndex, passowrdText
          .getText().toString());
       }
      }).show();
    break;
   case 4:
    Toast.makeText(WifiActivity.this, "连接成功!", Toast.LENGTH_SHORT)
      .show();
    wifi_result_textview.setText("当前网络:"
      + currentWifiInfo.getSSID() + " ip:"
      + WifiUtil.intToIp(currentWifiInfo.getIpAddress()));
    break;
   }
   super.handleMessage(msg);
  }

 };

}

3、辅助类:WifiUtil.java

/**
 *
 */
package com.android.util;

import java.util.List;

import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;

/**
 * @author passing
 *
 */
public class WifiUtil
{

 /**
  * 配置wifi
  *
  * @param SSID
  * @param Password
  * @param Type
  * @return
  */
 public static WifiConfiguration createWifiInfo(String SSID,
   String Password, int Type, WifiManager wifiManager)
 {
  WifiConfiguration config = new WifiConfiguration();
  config.allowedAuthAlgorithms.clear();
  config.allowedGroupCiphers.clear();
  config.allowedKeyManagement.clear();
  config.allowedPairwiseCiphers.clear();
  config.allowedProtocols.clear();
  config.SSID = "\"" + SSID + "\"";

  WifiConfiguration tempConfig = isExsits(SSID, wifiManager);
  if (tempConfig != null) {
   wifiManager.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;
 }

 /**
  * 判断wifi是否存在
  *
  * @param SSID
  * @param wifiManager
  * @return
  */
 private static WifiConfiguration isExsits(String SSID,
   WifiManager wifiManager)
 {
  List<WifiConfiguration> existingConfigs = wifiManager
    .getConfiguredNetworks();
  for (WifiConfiguration existingConfig : existingConfigs) {
   if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
    return existingConfig;
   }
  }
  return null;
 }

 /**
  * 转换IP地址
  *
  * @param i
  * @return
  */
 public static String intToIp(int i)
 {
  return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
    + "." + ((i >> 24) & 0xFF);
 }
}


 

  • 1
    点赞
  • 10
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值