Android connection WiFi and create a WiFi hotspot instance _android

Source: Internet
Author: User
Tags get ip stub bssid

The examples in this article describe ways to connect WiFi and create WiFi hotspots. Share to everyone for your reference, specific as follows:

Android's hotspot features are not visible, with the technology of reflection being done.

Eclipse settings Language is utf-8 to view Chinese comments

Code on:

Mainactivity.java

Package com.widget.hotspot; 
Import Android.os.Bundle; 
Import android.app.Activity; 
Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.content.IntentFilter; 
Import Android.util.Log; 
Import Android.view.Menu; 
Import Android.view.View; 
 
Import Android.widget.Button; 
   
  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) {super.oncreate (savedinstancestate); 
     
    Mcontext = this; 
     
    Setcontentview (R.layout.activity_main); 
    MBTN1 = (Button) Findviewbyid (R.id.button1); 
    MBTN2 = (Button) Findviewbyid (R.id.button2); 
    Mbtn1.settext ("Click Connect WiFi"); 
    Mbtn2.settext ("Click Create WiFi Hotspot"); Mbtn1.setonclicklistener (New Button.onclicklistener () {@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 MainActivity.this.unregisterReceiver (receiver); 
              @Override public Intent myregisterreceiver (broadcastreceiver receiver, Intentfilter filter) {//TODO auto-generated Method stub MainActivity.this.registerReceiver (rec 
            Eiver, filter); 
          return null; @Override public void onnotifywificonnected () {//TODO auto-generated Me 
            Thod stub log.v (TAG, "have connected success!"); 
          LOG.V (TAG, "###############################"); @Override public void onnotifywificonnectfailed () { 
            TODO auto-generated Method Stub log.v (TAG, "have connected failed!"); 
          LOG.V (TAG, "###############################"); 
        } 
        }; 
        Mwifiadmin.openwifi (); 
         
      Mwifiadmin.addnetwork (Mwifiadmin.createwifiinfo ("You_wifi", "MM123456", WIFIADMIN.TYPE_WPA)); 
     
    } 
    }); 
        Mbtn2.setonclicklistener (New Button.onclicklistener () {@Override public void OnClick (View v) { 
        TODO auto-generated Method Stub wifiapadmin Wifiap = new Wifiapadmin (mcontext); 
      WIFIAP.STARTWIFIAP ("\" Hotspot\ "", "hhhhhh123"); 
     
  } 
    }); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio 
    n Bar if it is present. 
    Getmenuinflater (). Inflate (R.menu.activity_main, menu); 
  return true; 
       
      @Override public void Onresume () {super.onresume (); LOG.D ("Rssi", "Registered"); 
       
      @Override public void OnPause () {super.onpause (); 
    LOG.D ("Rssi", "unregistered"); 
 } 
   
}

Wifiadmin.java

Package com.widget.hotspot; 
Import java.util.List; 
Import Java.util.Timer; 
Import Java.util.TimerTask; 
Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.content.IntentFilter; 
Import Android.net.ConnectivityManager; 
Import Android.net.NetworkInfo; 
Import Android.net.NetworkInfo.DetailedState; 
Import Android.net.wifi.ScanResult; 
Import android.net.wifi.WifiConfiguration; 
Import Android.net.wifi.WifiInfo; 
Import Android.net.wifi.WifiManager; 
Import Android.net.wifi.WifiManager.WifiLock; 
 
 
Import Android.util.Log; 
   
  Public abstract class Wifiadmin {private static final String TAG = "Wifiadmin"; 
  Private Wifimanager Mwifimanager; 
  Private Wifiinfo Mwifiinfo; 
  Scan out the list of network Connections private list<scanresult> mwifilist; 
 
  Private list<wificonfiguration> mwificonfiguration; 
   
  Private Wifilock Mwifilock; 
  Private String mpasswd = ""; 
   
  Private String Mssid = ""; PrivATE context mcontext = null; 
     
    Public Wifiadmin {mcontext = context; 
    Obtain Wifimanager Object Mwifimanager = (Wifimanager) context.getsystemservice (Context.wifi_service); 
     
    Obtain Wifiinfo Object mwifiinfo = Mwifimanager.getconnectioninfo (); 
  LOG.V (TAG, "getipaddress =" + mwifiinfo.getipaddress ()); //Open WiFi public void Openwifi () {if (!mwifimanager.iswifienabled ()) {mwifimanager.setwifienabled ( 
    true); //Turn off WiFi public void Closewifi () {if (mwifimanager.iswifienabled ()) {Mwifimanager.setwifiena 
    Bled (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 to the public void Addnetwork (Wificonfiguration WCG) {
    Register (); 
     
    WIFIAPADMIN.CLOSEWIFIAP (Mcontext); 
    int wcgid = Mwifimanager.addnetwork (WCG); 
  Boolean B = Mwifimanager.enablenetwork (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 | | | ssid.equals ("")) 
      {LOG.E (TAG, "Addnetwork () # # Nullpointer error!"); 
    Return } if (type!= type_no_passwd && type!= type_wep && type!= type_wpa) {log.e (TAG, "Addn 
    Etwork () # # unknown type = ' + type '); 
    } stoptimer (); 
     
    Unregister (); 
  Addnetwork (Createwifiinfo (SSID, passwd, type)); Private Broadcastreceiver Mbroadcastreceiver = new Broadcastreceiver () {@Override public void Onreceiv E (Context context, Intent Intent) {//TODO auto-generated method Stub if (Intent.getaction (). Equals (Wifimanager.rssi_changed_action)) {LOG.D (TAG, "RSSI CHANGED"); 
         
        There may be a gain, or have acquired LOG.D (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 () {LOG.V (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 () {LOG.V (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); 
Mtimer.schedule (mtimertask, 0, * 1000);/20s Mtimer.schedule (Mtimertask, 30 * 1000);  Private TimerTask Mtimertask = new TimerTask () {@Override public void run () {//TODO A 
      uto-generated method Stub log.e (TAG, "Timer out!"); 
      Onnotifywificonnectfailed (); 
    Unregister (); 
   
  } 
  }; 
      private void Stoptimer () {if (Mtimer!= null) {mtimer.cancel (); 
    Mtimer = null; 
      @Override protected void Finalize () {try {super.finalize (); 
    Unregister (); 
    catch (Throwable e) {//TODO auto-generated catch block E.printstacktrace (); } Public wificonfiguration Createwifiinfo (string SSID, string password, int type) {LOG.V (TAG, "SSI") 
     
    D = "+ SSID +" # # Password = + Password + "# # Type =" + 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);  ///Divided into three cases: 1 no password 2 with WEP encryption 3 with WPA encryption if (type = = TYPE_NO_PASSWD) {//Wificipher_nopass config.wepkeys[0] 
      = ""; 
      Config.allowedKeyManagement.set (WifiConfiguration.KeyMgmt.NONE); 
       
    Config.weptxkeyindex = 0; 
      else if (type = = TYPE_WEP) {//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; 
      else if (type = = TYPE_WPA) {//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; 
  public static final int wifi_connected = 0x01; Public Static final int wifi_connect_failed = 0x02; 
  public static final int wifi_connecting = 0x03; /** * Determine if WiFi connection is successful, not network * * @param context * @return/public int iswificontected (context con Text) {Connectivitymanager Connectivitymanager = (connectivitymanager) context. Getsystemservice (context.co 
    Nnectivity_service); 
     
    Networkinfo wifinetworkinfo = Connectivitymanager. Getnetworkinfo (Connectivitymanager.type_wifi); 
    LOG.V (TAG, "isconnectedorconnecting =" + wifinetworkinfo.isconnectedorconnecting ()); 
    LOG.D (TAG, "wifinetworkinfo.getdetailedstate () =" + wifinetworkinfo.getdetailedstate ());  if (wifinetworkinfo.getdetailedstate () = = Detailedstate.obtaining_ipaddr | | wifinetworkinfo.getdetailedstate () = = 
    detailedstate.connecting) {return wifi_connecting; 
    else if (wifinetworkinfo.getdetailedstate () = = detailedstate.connected) {return wifi_connected; else {log.d (TAG, "getDetailedstate () = = "+ wifinetworkinfo.getdetailedstate ()); 
    return wifi_connect_failed; } private Wificonfiguration Isexsits (String SSID) {list<wificonfiguration> Existingconfigs = Mwifi 
    Manager.getconfigurednetworks (); for (Wificonfiguration existingconfig:existingconfigs) {if (ExistingConfig.SSID.equals ("\" + SSID + "\")/*&am 
      p;& existingConfig.preSharedKey.equals ("\" "+ Password +" \ ")" * *) {return existingconfig; 
  } return null; 
    //Disconnect the network public void Disconnectwifi (int netid) {mwifimanager.disablenetwork (NetID) of the specified ID; 
  Mwifimanager.disconnect (); 
  //Check the current wifi status public int checkstate () {return mwifimanager.getwifistate (); 
  }//Lock Wifilock public void Acquirewifilock () {mwifilock.acquire (); }//unlock wifilock public void Releasewifilock () {//Judgment Time Lock if (Mwifilock.isheld ()) {Mwifilock.acq 
    Uire (); }//ChuangBuild a wifilock public void Creatwifilock () {mwifilock = Mwifimanager.createwifilock ("Test"); 
  //Get the configured network public list<wificonfiguration> GetConfiguration () {return mwificonfiguration; //Specify configured network connection public void connectconfiguration (int index) {//index greater than configured network index return if (Index > Mwifico 
    Nfiguration.size ()) {return; 
  ///Connect the configured network Mwifimanager.enablenetwork (Mwificonfiguration.get (Index) Networkid, true) with the specified ID. 
    public void Startscan () {Mwifimanager.startscan (); 
    Mwifilist = Mwifimanager.getscanresults (); 
  Mwificonfiguration = Mwifimanager.getconfigurednetworks (); 
  //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 < mwifilist.size (); i++) {StringBuilder. Append ("index_" + new Integer (i +1). toString () + ":"); Converts the Scanresult information into a string package//including: BSSID, SSID, capabilities, frequency, level stringbuilder.append (MWIFILIST.G 
      ET (i)). ToString ()); 
    Stringbuilder.append ("n"); 
  return stringBuilder; //Get MAC address public String getmacaddress () {return (Mwifiinfo = = null)? 
  "NULL": mwifiinfo.getmacaddress (); ///Get access point Bssid public String Getbssid () {return (Mwifiinfo = null)? 
  "NULL": Mwifiinfo.getbssid (); 
  //Get IP address public int getipaddress () {return (Mwifiinfo = = null)? 0:mwifiinfo.getipaddress (); 
  //Get the connection ID public int Getnetworkid () {return (Mwifiinfo = null)? 0:mwifiinfo.getnetworkid (); ///Get Wifiinfo All packets public String Getwifiinfo () {return (Mwifiinfo = null)? 
  "NULL": mwifiinfo.tostring (); 
 } 
}

Wifiapadmin.java

Package com.widget.hotspot; 
Import java.lang.reflect.InvocationTargetException; 
Import Java.lang.reflect.Method; 
Import Java.util.Timer; 
 
Import Java.util.TimerTask; 
Import Android.content.Context; 
Import android.net.wifi.WifiConfiguration; 
Import Android.net.wifi.WifiManager; 
 
Import Android.util.Log; 
   
  /** * Create hotspot */public class Wifiapadmin {public static final String TAG = "Wifiapadmin"; public static void Closewifiap {Wifimanager Wifimanager = (wifimanager) context.getsystemservice (Co ntext.  
    Wifi_service); 
  CLOSEWIFIAP (Wifimanager); 
   
  Private Wifimanager Mwifimanager = null; 
  Private context mcontext = null; 
     
    Public Wifiapadmin {mcontext = context;  
     
    Mwifimanager = (Wifimanager) mcontext.getsystemservice (Context.wifi_service); 
  CLOSEWIFIAP (Mwifimanager); 
  Private String Mssid = ""; 
  Private String mpasswd = ""; public void Startwifiap (String SSID, STring passwd) {mssid = SSID; 
     
    MPASSWD = passwd; 
    if (mwifimanager.iswifienabled ()) {mwifimanager.setwifienabled (false); 
     
    } STRATWIFIAP (); Mytimercheck Timercheck = new Mytimercheck () {@Override public void dotimercheckwork () {/ /TODO auto-generated Method stub if (iswifiapenabled (Mwifimanager)) {LOG.V (TAG, "Wifi Enab 
          LED success! "); 
        This.exit (); 
        else {log.v (TAG, "Wifi enabled failed!"); @Override public void Dotimeoutwork () {//TODO auto-generated method stub th 
      Is.exit (); 
    } 
    }; 
     
  Timercheck.start (15, 1000); 
    public void Stratwifiap () {method method1 = null; try {method1 = Mwifimanager.getclass (). GetMethod ("setwifiapenabled", Wificonfiguration.class, BOOLEAN.C 
      LASS); Wificonfiguration netconfig = new Wificonfiguration (); 
      Netconfig.ssid = Mssid; 
 
      Netconfig.presharedkey = mpasswd; 
      Netconfig.allowedauthalgorithms. Set (WifiConfiguration.AuthAlgorithm.OPEN); 
      NetConfig.allowedProtocols.set (WifiConfiguration.Protocol.RSN); 
      NetConfig.allowedProtocols.set (WifiConfiguration.Protocol.WPA); 
      Netconfig.allowedkeymanagement. Set (WifiConfiguration.KeyMgmt.WPA_PSK); 
      Netconfig.allowedpairwiseciphers. Set (WifiConfiguration.PairwiseCipher.CCMP); 
      Netconfig.allowedpairwiseciphers. Set (WifiConfiguration.PairwiseCipher.TKIP); 
      Netconfig.allowedgroupciphers. Set (WifiConfiguration.GroupCipher.CCMP); 
 
      Netconfig.allowedgroupciphers. Set (WifiConfiguration.GroupCipher.TKIP); 
 
    Method1.invoke (Mwifimanager, Netconfig, true); 
    catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace (); catch (Illegalaccessexception e) {//TODO auto-generated Catch block E.printstacktrace (); 
    catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace (); 
    catch (SecurityException e) {//TODO auto-generated catch block E.printstacktrace (); 
    catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace ();  }} private static void Closewifiap (Wifimanager wifimanager) {if (iswifiapenabled (Wifimanager)) {try 
        {Method method = Wifimanager.getclass (). GetMethod ("Getwifiapconfiguration"); 
 
        Method.setaccessible (TRUE); 
 
        wificonfiguration config = (wificonfiguration) method.invoke (Wifimanager); 
        Method method2 = Wifimanager.getclass (). GetMethod ("setwifiapenabled", Wificonfiguration.class, Boolean.class); 
      Method2.invoke (Wifimanager, config, false); 
      catch (Nosuchmethodexception e) {//TODO auto-generated catch block  E.printstacktrace (); 
      catch (IllegalArgumentException e) {//TODO auto-generated catch block E.printstacktrace (); 
      catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace (); 
      catch (InvocationTargetException e) {//TODO auto-generated catch block E.printstacktrace (); }} private static Boolean iswifiapenabled (Wifimanager wifimanager) {try {method method = Wif 
      Imanager.getclass (). GetMethod ("iswifiapenabled"); 
      Method.setaccessible (TRUE); 
 
    Return (Boolean) Method.invoke (Wifimanager); 
    catch (Nosuchmethodexception e) {//TODO auto-generated catch block E.printstacktrace (); 
    catch (Exception e) {e.printstacktrace (); 
  return false; 
 } 
 
}

Mytimecheck.java

Package com.widget.hotspot; 
  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. 
   
  * * 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 {mthread.sleep (msleeptime); 
              catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); 
            Exit (); 
          } else {dotimeoutwork (); 
} 
        } 
      }    }); 
   /** * Start * @param times how many times would check? 
   * @param sleeptime MS, Every check sleep time. 
    */public void start (int timeoutcount, int sleeptime) {mtimeoutcount = Timeoutcount; 
     
    Msleeptime = Sleeptime; 
  Mthread.start (); 
  public void exit () {Mexitflag = true; 
 } 
   
}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.