SoFunction
Updated on 2025-03-11

Android Connect Wifi and Create Wifi Hotspot

This article describes how to connect Wifi and create Wifi hotspots. Share it for your reference, as follows:

The hotspot function of Android is not visible, and it is not done with reflection technology.

Eclipse language is set to utf-8 to view Chinese comments

On code:


package ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
public class MainActivity extends Activity { 
 
  public static final String TAG = "MainActivity"; 
   
  private Button mBtn1, mBtn2; 
   
  private WifiAdmin mWifiAdmin; 
   
  private Context mContext = null; 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    (savedInstanceState); 
     
    mContext = this; 
     
    setContentView(.activity_main); 
     
    mBtn1 = (Button)findViewById(.button1); 
    mBtn2 = (Button)findViewById(.button2); 
    ("Click to connect to Wifi"); 
    ("Click to create a Wifi hotspot"); 
    (new () { 
       
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
 
        mWifiAdmin = new WifiAdmin(mContext) { 
           
          @Override 
          public void myUnregisterReceiver(BroadcastReceiver receiver) { 
            // TODO Auto-generated method stub 
            (receiver); 
          } 
           
          @Override 
          public Intent myRegisterReceiver(BroadcastReceiver receiver, 
              IntentFilter filter) { 
            // TODO Auto-generated method stub 
            (receiver, filter); 
            return null; 
          } 
           
          @Override 
          public void onNotifyWifiConnected() { 
            // TODO Auto-generated method stub 
            (TAG, "have connected success!"); 
            (TAG, "###############################"); 
          } 
           
          @Override 
          public void onNotifyWifiConnectFailed() { 
            // TODO Auto-generated method stub 
            (TAG, "have connected failed!"); 
            (TAG, "###############################"); 
          } 
        }; 
        (); 
        (("YOU_WIFI", "MM123456", WifiAdmin.TYPE_WPA)); 
         
      } 
    }); 
     
    (new () { 
       
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
         
        WifiApAdmin wifiAp = new WifiApAdmin(mContext); 
        ("\"HotSpot\"", "hhhhhh123"); 
      } 
    }); 
     
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(.activity_main, menu); 
    return true; 
  } 
 
   @Override 
    public void onResume() { 
      (); 
       
      ("Rssi", "Registered"); 
    } 
 
    @Override 
    public void onPause() { 
      (); 
       
      ("Rssi", "Unregistered"); 
    } 
   
} 


package ;  
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
 
 
public abstract class WifiAdmin { 
   
  private static final String TAG = "WifiAdmin"; 
   
  private WifiManager mWifiManager; 
  private WifiInfo mWifiInfo; 
  // Scanned network connection list  private List<ScanResult> mWifiList; 
  private List<WifiConfiguration> mWifiConfiguration; 
 
  private WifiLock mWifiLock; 
   
  private String mPasswd = ""; 
  private String mSSID = ""; 
   
  private Context mContext = null; 
 
  public WifiAdmin(Context context) { 
     
    mContext = context; 
     
    // Get the WifiManager object    mWifiManager = (WifiManager) (Context.WIFI_SERVICE); 
    // Get WifiInfo object    mWifiInfo = (); 
     
    (TAG, "getIpAddress = " + ()); 
  } 
 
  // Turn on WIFI  public void openWifi() { 
    if (!()) { 
      (true); 
    } 
  } 
 
  // Turn off WIFI  public void closeWifi() { 
    if (()) { 
      (false); 
    } 
  } 
 
  public abstract Intent myRegisterReceiver(BroadcastReceiver receiver, IntentFilter filter); 
   
  public abstract void myUnregisterReceiver(BroadcastReceiver receiver); 
   
  public abstract void onNotifyWifiConnected(); 
   
  public abstract void onNotifyWifiConnectFailed(); 
   
  // Add a network and connect  public void addNetwork(WifiConfiguration wcg) { 
     
    register(); 
     
    (mContext); 
     
    int wcgID = (wcg); 
    boolean b = (wcgID, true); 
  } 
   
  public static final int TYPE_NO_PASSWD = 0x11; 
  public static final int TYPE_WEP = 0x12; 
  public static final int TYPE_WPA = 0x13; 
   
  public void addNetwork(String ssid, String passwd, int type) { 
    if (ssid == null || passwd == null || ("")) { 
      (TAG, "addNetwork() ## nullpointer error!"); 
      return; 
    } 
     
    if (type != TYPE_NO_PASSWD && type != TYPE_WEP && type != TYPE_WPA) { 
      (TAG, "addNetwork() ## unknown type = " + type); 
    } 
     
    stopTimer(); 
    unRegister(); 
     
    addNetwork(createWifiInfo(ssid, passwd, type)); 
  } 
 
  private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 
 
    @Override 
    public void onReceive(Context context, Intent intent) { 
      // TODO Auto-generated method stub 
      if (().equals(WifiManager.RSSI_CHANGED_ACTION)) { 
        (TAG, "RSSI changed"); 
         
        //It may be that it is being retrieved, or it has been retrieved        (TAG, " intent is " + WifiManager.RSSI_CHANGED_ACTION); 
         
        if (isWifiContected(mContext) == WIFI_CONNECTED) { 
          stopTimer(); 
          onNotifyWifiConnected(); 
          unRegister(); 
        } else if (isWifiContected(mContext) == WIFI_CONNECT_FAILED) { 
          stopTimer(); 
          closeWifi(); 
          onNotifyWifiConnectFailed(); 
          unRegister(); 
        } else if (isWifiContected(mContext) == WIFI_CONNECTING) { 
           
        } 
      } 
    } 
  }; 
   
  private final int STATE_REGISTRING = 0x01; 
  private final int STATE_REGISTERED = 0x02; 
  private final int STATE_UNREGISTERING = 0x03; 
  private final int STATE_UNREGISTERED = 0x04; 
   
  private int mHaveRegister = STATE_UNREGISTERED; 
  private synchronized void register() { 
    (TAG, "register() ##mHaveRegister = " + mHaveRegister); 
 
    if (mHaveRegister == STATE_REGISTRING  
        || mHaveRegister == STATE_REGISTERED) { 
      return ; 
    } 
     
    mHaveRegister = STATE_REGISTRING; 
    myRegisterReceiver(mBroadcastReceiver, new IntentFilter(WifiManager.RSSI_CHANGED_ACTION)); 
    mHaveRegister = STATE_REGISTERED; 
     
    startTimer(); 
  } 
   
  private synchronized void unRegister() { 
    (TAG, "unRegister() ##mHaveRegister = " + mHaveRegister); 
     
    if (mHaveRegister == STATE_UNREGISTERED  
        || mHaveRegister == STATE_UNREGISTERING) { 
      return ; 
    } 
     
    mHaveRegister = STATE_UNREGISTERING; 
    myUnregisterReceiver(mBroadcastReceiver); 
    mHaveRegister = STATE_UNREGISTERED; 
  } 
   
  private Timer mTimer = null; 
  private void startTimer() { 
    if (mTimer != null) { 
      stopTimer(); 
    } 
     
    mTimer = new Timer(true); 
//   (mTimerTask, 0, 20 * 1000);// 20s 
    (mTimerTask, 30 * 1000); 
  } 
   
  private TimerTask mTimerTask = new TimerTask() { 
     
    @Override 
    public void run() { 
      // TODO Auto-generated method stub 
      (TAG, "timer out!"); 
      onNotifyWifiConnectFailed(); 
      unRegister(); 
    } 
  }; 
   
  private void stopTimer() { 
    if (mTimer != null) { 
      (); 
      mTimer = null; 
    } 
  } 
   
  @Override 
  protected void finalize() { 
    try { 
      (); 
      unRegister(); 
    } catch (Throwable e) { 
      // TODO Auto-generated catch block 
      (); 
    } 
  } 
   
  public WifiConfiguration createWifiInfo(String SSID, String password, int type) { 
     
    (TAG, "SSID = " + SSID + "## Password = " + password + "## Type = " + type); 
     
    WifiConfiguration config = new WifiConfiguration(); 
    (); 
    (); 
    (); 
    (); 
    (); 
     = "\"" + SSID + "\""; 
 
    WifiConfiguration tempConfig = (SSID); 
    if (tempConfig != null) { 
      (); 
    } 
     
    // It is divided into three situations: 1. No password 2. Encrypted with wep 3. Encrypted with wpa    if (type == TYPE_NO_PASSWD) {// WIFICIPHER_NOPASS 
      [0] = ""; 
      (); 
       = 0; 
       
    } else if (type == TYPE_WEP) { // WIFICIPHER_WEP  
       = true; 
      [0] = "\"" + password + "\""; 
       
          .set(); 
      (); 
      (); 
      (.WEP40); 
       
          .set(.WEP104); 
      (); 
       = 0; 
    } else if (type == TYPE_WPA) {  // WIFICIPHER_WPA 
       = "\"" + password + "\""; 
       = true; 
       
          .set(); 
      (); 
      (.WPA_PSK); 
       
          .set(); 
      // (); 
      (); 
       
          .set(); 
       = ; 
    }  
     
    return config; 
  } 
   
  public static final int WIFI_CONNECTED = 0x01; 
  public static final int WIFI_CONNECT_FAILED = 0x02; 
  public static final int WIFI_CONNECTING = 0x03; 
  /**
    * Determine whether the wifi is connected successfully, not network
    *
    * @param context
    * @return
    */ 
  public int isWifiContected(Context context) { 
    ConnectivityManager connectivityManager = (ConnectivityManager) context 
        .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo wifiNetworkInfo = connectivityManager 
        .getNetworkInfo(ConnectivityManager.TYPE_WIFI); 
     
    (TAG, "isConnectedOrConnecting = " + ()); 
    (TAG, "() = " + ()); 
    if (() == DetailedState.OBTAINING_IPADDR 
        || () == ) { 
      return WIFI_CONNECTING; 
    } else if (() == ) { 
      return WIFI_CONNECTED; 
    } else { 
      (TAG, "getDetailedState() == " + ()); 
      return WIFI_CONNECT_FAILED; 
    } 
  } 
   
  private WifiConfiguration IsExsits(String SSID) { 
    List<WifiConfiguration> existingConfigs = (); 
    for (WifiConfiguration existingConfig : existingConfigs) { 
      if (("\"" + SSID + "\"") /*&& ("\"" + password + "\"")*/) { 
        return existingConfig; 
      } 
    } 
    return null; 
  } 
   
 
 
  // Disconnect the network with the specified ID  public void disconnectWifi(int netId) { 
    (netId); 
    (); 
  } 
   
  // Check the current WIFI status  public int checkState() { 
    return (); 
  } 
 
  // Lock WifiLock  public void acquireWifiLock() { 
    (); 
  } 
 
  // Unlock WifiLock  public void releaseWifiLock() { 
    // Lock when judging    if (()) { 
      (); 
    } 
  } 
 
  // Create a WifiLock  public void creatWifiLock() { 
    mWifiLock = ("Test"); 
  } 
 
  // Get configured network  public List<WifiConfiguration> getConfiguration() { 
    return mWifiConfiguration; 
  } 
 
  // Specify the configured network to connect  public void connectConfiguration(int index) { 
    // Return the index larger than the configured network index    if (index > ()) { 
      return; 
    } 
    // Connect to the network with the specified ID    ((index).networkId, 
        true); 
  } 
 
  public void startScan() { 
    (); 
    mWifiList = (); 
    mWifiConfiguration = (); 
  } 
 
  // Get the network list  public List<ScanResult> getWifiList() { 
    return mWifiList; 
  } 
 
  // View scan results  public StringBuilder lookUpScan() { 
    StringBuilder stringBuilder = new StringBuilder(); 
    for (int i = 0; i < (); i++) { 
      stringBuilder 
          .append("Index_" + new Integer(i + 1).toString() + ":"); 
      // Convert ScanResult information into a string package      // These include: BSSID, SSID, capabilities, frequency, level      (((i)).toString()); 
      ("/n"); 
    } 
    return stringBuilder; 
  } 
 
  // Get the MAC address  public String getMacAddress() { 
    return (mWifiInfo == null) ? "NULL" : (); 
  } 
 
  // Get the BSSID of the access point  public String getBSSID() { 
    return (mWifiInfo == null) ? "NULL" : (); 
  } 
 
  // Get the IP address  public int getIPAddress() { 
    return (mWifiInfo == null) ? 0 : (); 
  } 
 
  // Get the connection ID  public int getNetworkId() { 
    return (mWifiInfo == null) ? 0 : (); 
  } 
 
  // Get all the information packages from WifiInfo  public String getWifiInfo() { 
    return (mWifiInfo == null) ? "NULL" : (); 
  } 
} 


package ; 
 
import ; 
import ; 
import ; 
import ; 
 
import ; 
import ; 
import ; 
import ; 
 
/**
  * Create hotspots
  *
  */ 
public class WifiApAdmin { 
  public static final String TAG = "WifiApAdmin"; 
   
  public static void closeWifiAp(Context context) { 
    WifiManager wifiManager = (WifiManager) (Context.WIFI_SERVICE);  
    closeWifiAp(wifiManager); 
  } 
   
  private WifiManager mWifiManager = null; 
   
  private Context mContext = null; 
  public WifiApAdmin(Context context) { 
    mContext = context; 
     
    mWifiManager = (WifiManager) (Context.WIFI_SERVICE);  
     
    closeWifiAp(mWifiManager); 
  } 
   
  private String mSSID = ""; 
  private String mPasswd = ""; 
  public void startWifiAp(String ssid, String passwd) { 
    mSSID = ssid; 
    mPasswd = passwd; 
     
    if (()) { 
      (false); 
    }  
     
    stratWifiAp(); 
     
    MyTimerCheck timerCheck = new MyTimerCheck() { 
       
      @Override 
      public void doTimerCheckWork() { 
        // TODO Auto-generated method stub 
         
        if (isWifiApEnabled(mWifiManager)) { 
          (TAG, "Wifi enabled success!"); 
          (); 
        } else { 
          (TAG, "Wifi enabled failed!"); 
        } 
      } 
 
      @Override 
      public void doTimeOutWork() { 
        // TODO Auto-generated method stub 
        (); 
      } 
    }; 
    (15, 1000); 
     
  } 
 
  public void stratWifiAp() { 
    Method method1 = null; 
    try { 
      method1 = ().getMethod("setWifiApEnabled", 
          , ); 
      WifiConfiguration netConfig = new WifiConfiguration(); 
 
       = mSSID; 
       = mPasswd; 
 
       
          .set(); 
      (); 
      (); 
       
          .set(.WPA_PSK); 
       
          .set(); 
       
          .set(); 
       
          .set(); 
       
          .set(); 
 
      (mWifiManager, netConfig, true); 
 
    } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      (); 
    } catch (IllegalAccessException e) { 
      // TODO Auto-generated catch block 
      (); 
    } catch (InvocationTargetException e) { 
      // TODO Auto-generated catch block 
      (); 
    } catch (SecurityException e) { 
      // TODO Auto-generated catch block 
      (); 
    } catch (NoSuchMethodException e) { 
      // TODO Auto-generated catch block 
      (); 
    } 
  } 
 
  private static void closeWifiAp(WifiManager wifiManager) { 
    if (isWifiApEnabled(wifiManager)) { 
      try { 
        Method method = ().getMethod("getWifiApConfiguration"); 
        (true); 
 
        WifiConfiguration config = (WifiConfiguration) (wifiManager); 
 
        Method method2 = ().getMethod("setWifiApEnabled", , ); 
        (wifiManager, config, false); 
      } catch (NoSuchMethodException e) { 
        // TODO Auto-generated catch block 
        (); 
      } catch (IllegalArgumentException e) { 
        // TODO Auto-generated catch block 
        (); 
      } catch (IllegalAccessException e) { 
        // TODO Auto-generated catch block 
        (); 
      } catch (InvocationTargetException e) { 
        // TODO Auto-generated catch block 
        (); 
      } 
    } 
  } 
 
  private static boolean isWifiApEnabled(WifiManager wifiManager) { 
    try { 
      Method method = ().getMethod("isWifiApEnabled"); 
      (true); 
      return (Boolean) (wifiManager); 
 
    } catch (NoSuchMethodException e) { 
      // TODO Auto-generated catch block 
      (); 
    } catch (Exception e) { 
      (); 
    } 
 
    return false; 
  } 
 
} 


package ; 
public abstract class MyTimerCheck { 
  private int mCount = 0; 
  private int mTimeOutCount = 1; 
  private int mSleepTime = 1000; // 1s 
  private boolean mExitFlag = false; 
  private Thread mThread = null; 
   
  /** 
   * Do not process UI work in this. 
   */ 
  public abstract void doTimerCheckWork(); 
   
  public abstract void doTimeOutWork(); 
   
  public MyTimerCheck() { 
    mThread = new Thread(new Runnable() { 
       
      @Override 
      public void run() { 
        // TODO Auto-generated method stub 
        while (!mExitFlag) { 
          mCount++; 
          if (mCount < mTimeOutCount) { 
            doTimerCheckWork(); 
            try { 
              (mSleepTime); 
            } catch (InterruptedException e) { 
              // TODO Auto-generated catch block 
              (); 
              exit(); 
            } 
          } else { 
            doTimeOutWork(); 
          } 
        } 
      } 
    }); 
  } 
   
  /** 
   * start 
   * @param times How many times will check? 
   * @param sleepTime ms, Every check sleep time. 
   */ 
  public void start(int timeOutCount, int sleepTime) { 
    mTimeOutCount = timeOutCount; 
    mSleepTime = sleepTime; 
     
    (); 
  } 
   
  public void exit() { 
    mExitFlag = true; 
  } 
   
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.