亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Android編程實現wifi掃描及連接的方法

發布時間:2020-08-27 19:57:05 來源:腳本之家 閱讀:260 作者:遲做總比不做強 欄目:移動開發

本文實例講述了Android編程實現wifi掃描及連接的方法。分享給大家供大家參考,具體如下:

主界面,搜索附近WIFI信息

/**
 * 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);
    }
  }
}

/**
 * 連接指定的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();
  }
}

工具類:

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

—–相關布局文件————–

主頁面

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

連接頁面

<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

<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的展示

<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程序設計有所幫助。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

韶关市| 昆明市| 台山市| 潢川县| 古丈县| 永嘉县| 维西| 开化县| 邢台县| 淮滨县| 武强县| 巨野县| 湟源县| 永吉县| 招远市| 西林县| 长阳| 威宁| 新平| 枣强县| 互助| 南靖县| 邹城市| 嘉鱼县| 昌邑市| 长乐市| 长泰县| 台南市| 张掖市| 宜宾县| 崇阳县| 肇州县| 隆德县| 海阳市| 尉犁县| 安阳县| 清苑县| 枣庄市| 河池市| 杂多县| 西盟|