The magic of QR code: Zxing allows you to share your Wi-Fi account and password, and zxingwifi

Source: Internet
Author: User
Tags addall bssid

The magic of QR code: Zxing allows you to share your Wi-Fi account and password, and zxingwifi

QR code is a carrier for carrying information. It can be used to transmit business cards, URLs, and product information. This article describes another use of QR codes: Sharing Wi-Fi accounts and passwords through QR codes.

For more information about the QR code, see: QR code generation details and principles.

Imagine a scenario where a group of people go to the same restaurant or have a meeting together. Some people have already visited and used the Wi-Fi account for that scenario, so the Wi-Fi can be directly connected to the mobile phone, but some of them are the first to connect to wifi, at this time, we generally use someone to tell the Wi-Fi account and password and then manually log in, but the problem is that sometimes people who have already connected to wifi do not remember the Wi-Fi password. This article combines this scenario, a demo of sharing the Wi-Fi account and password is provided that both parties need to install the app, and the sharing wifi party needs to have the root permission (currently yes, you can also share the wifi client as a hotspot, and then share the hotspot with others, which can be researched by yourself), which reduces the trouble of manually entering the password.


This article mainly introduces two core functions of wifi sharing through QR code:

1. Obtain the wifi account, password, and encryption method connected to the local machine;

2. Generate a QR code for the specified content and scan the QR code to parse the information contained in the Code.


1. Obtain the wifi account, password, and encryption method connected to the local machine:

All things can be done through the following class:

Public class WifiAdmin {public WifiAdmin (Context context) {mWifiManager = (WifiManager) context. getSystemService (Context. WIFI_SERVICE); mWifiInfo = mWifiManager. getConnectionInfo () ;}// enable WIFI public void openWifi () {if (! MWifiManager. isWifiEnabled () {mWifiManager. setWifiEnabled (true) ;}// disable WIFI public void closeWifi () {if (mWifiManager. isWifiEnabled () {mWifiManager. setWifiEnabled (false) ;}// check the current WIFI status public int checkState () {return mWifiManager. getWifiState ();} // lock WifiLock public void acquireWifiLock () {mWifiLock. acquire ();} // unlock WifiLock public void releaseWifiLock () {// lock if (mWifiLock when judging. I SHeld () {mWifiLock. acquire () ;}}// create a WifiLock public void creatWifiLock () {mWifiLock = mWifiManager. createWifiLock ("Test");} // The configured public List <WifiConfiguration> getConfiguration () {return mWifiConfiguration ;} // specify the configured network to connect to the public void connectConfiguration (int index) {// if (index> mWifiConfiguration is returned if the index is greater than the configured network index. size () {return;} // connect the network mWifiManager with the specified ID. enableNetwork (MWifiConfiguration. get (index ). networkId, true);} public void startScan () {mWifiManager. startScan (); // obtain the scan result mWifiList = mWifiManager. getScanResults (); // obtain the configured network connection mWifiConfiguration = mWifiManager. getConfiguredNetworks ();} // obtain the public List of networks <ScanResult> getWifiList () {return mWifiList;} // view the scan result @ SuppressLint ("UseValueOf") public StringBuilder lookUpScan () {StringBuilder stringBuilde R = new StringBuilder (); for (int I = 0; I <mWifiList. size (); I ++) {stringBuilder. append ("Index _" + new Integer (I + 1 ). toString () + ":"); // converts ScanResult information into a string package that includes BSSID, SSID, capabilities, frequency, and level stringBuilder. append (mWifiList. get (I )). toString (); stringBuilder. append ("/n") ;}return stringBuilder ;}// obtain the MAC address public String getMacAddress () {return (mWifiInfo = null )? "NULL": mWifiInfo. getMacAddress () ;}// obtain the Access Point's BSSID public String getBSSID () {return (mWifiInfo = null )? "NULL": mWifiInfo. getBSSID () ;}// obtain the IP address public int getIPAddress () {return (mWifiInfo = null )? 0: mWifiInfo. getIpAddress () ;}// obtain the connection ID public int getNetworkId () {return (mWifiInfo = null )? 0: mWifiInfo. getNetworkId () ;}// get all information packages of WifiInfo public WifiInfo getWifiInfo () {return mWifiInfo ;}// Add a network and connect to public void addNetwork (WifiConfiguration wcg) {int wcgID = mWifiManager. addNetwork (wcg); boolean B = mWifiManager. enableNetwork (wcgID, true); System. out. println ("a --" + wcgID); System. out. println ("B --" + B);} // disconnect the Network public void disconnectWifi (int netId) {mWifiManager. disabl ENetwork (netId); mWifiManager. disconnect () ;}// then an actual application method. Only the password is verified: // There are three scenarios: 1 No password 2 wep encryption 3 wpa encryption 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. allowedProtoc Ols. clear (); config. SSID = "\" "+ SSID +" \ ""; WifiConfiguration tempConfig = this. IsExsits (SSID); if (tempConfig! = Null) {mWifiManager. removeNetwork (tempConfig. networkId);} if (type = 1) {// WIFICIPHER_NOPASSconfig.wepKeys [0] = ""; config. allowedKeyManagement. set (WifiConfiguration. keyMgmt. NONE); config. wepTxKeyIndex = 0;} if (type = 2) {// WIFICIPHER_WEPconfig.hiddenSSID = true; config. wepKeys [0] = "\" "+ password +" \ ""; config. allowedAuthAlgorithms. set (WifiConfiguration. authAlgorithm. SHARED); config. allowedGroup Ciphers. 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_WPAconfig.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. allowed GroupCiphers. 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 (); if (null = existingConfigs) {return null;} for (WifiConfiguration existingConfig: ExistingConfigs) {System. out. println ("existingConfig =" + existingConfig. toString (); if (existingConfig. SSID. equals ("\" "+ SSID +" \ "") {System. out. println ("existingConfig. SSID = "+ existingConfig. SSID + "SSID =" + SSID); return existingConfig ;}} return null;} public List <UserWifiInfo> getUserWifiInfoList () throws Exception {List <UserWifiInfo> wifiInfos = new ArrayList <UserWifiInfo> (); Pr Ocess process = null; DataOutputStream dataOutputStream = null; DataInputStream dataInputStream = null; StringBuffer wifiConf = new StringBuffer (); try {process = runtime.getruntime(cmd.exe c ("su "); dataOutputStream = new DataOutputStream (process. getOutputStream (); dataInputStream = new DataInputStream (process. getInputStream (); dataOutputStream. writeBytes ("cat/data/misc/wifi /*. conf \ n "); dataOutpu TStream. writeBytes ("exit \ n"); dataOutputStream. flush (); InputStreamReader inputStreamReader = new InputStreamReader (dataInputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); String line = null; while (line = bufferedReader. readLine ())! = Null) {wifiConf. append (line);} bufferedReader. close (); inputStreamReader. close (); process. waitFor ();} catch (Exception e) {throw e;} finally {try {if (dataOutputStream! = Null) {dataOutputStream. close ();} if (dataInputStream! = Null) {dataInputStream. close ();} process. destroy () ;}catch (Exception e) {throw e ;}} Pattern network = Pattern. compile ("network =\{ ([^ \}] +) \\}", Pattern. DOTALL); Matcher networkMatcher = network. matcher (wifiConf. toString (); while (networkMatcher. find () {String networkBlock = networkMatcher. group (); Pattern ssid = Pattern. compile ("ssid = \" ([^ \ "] +) \" "); Matcher ssidMatcher = ssid. matcher (networkBlock); if (ssidMatcher. find () {UserWifiInfo wifiInfo = new UserWifiInfo (); wifiInfo. ssid = ssidMatcher. group (1); Pattern psk = Pattern. compile ("psk = \" ([^ \ "] +) \" "); Matcher pskMatcher = psk. matcher (networkBlock); if (pskMatcher. find () {wifiInfo. password = pskMatcher. group (1);} else {wifiInfo. password = "no Password";} wifiInfos. add (wifiInfo) ;}} return wifiInfos;} private WifiManager mWifiManager = null; private WifiInfo mWifiInfo = null; private List <ScanResult> mWifiList = null; private List <WifiConfiguration> mWifiConfiguration = null; private WifiLock mWifiLock = null ;}

When using various features of wifi, remember to add the corresponding permissions:

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >    </uses-permission>    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >    </uses-permission>


2. Generate a QR code for the specified content and scan the QR code to parse the information contained in the Code:

This article uses the open-source QR code project zxing. For more information about zxing, see QR code and barcode scan-use Google ZXing

(1) generate a QR code using the specified content as follows:

@ SuppressWarnings ("deprecation") private void generate (String result) {if (TextUtils. isEmpty (result) {return;} try {// judge result validity if (result = null | "". equals (result) | result. length () <1) {return;} Hashtable <EncodeHintType, String> hints = new Hashtable <EncodeHintType, String> (); hints. put (EncodeHintType. CHARACTER_SET, "UTF-8"); // convert image data using a matrix to convert BitMatrix bitMatrix = new QRCodeWriter (). encode (result, BarcodeFormat. QR_CODE, QR_WIDTH, QR_HEIGHT, hints); int [] pixels = new int [QR_WIDTH * QR_HEIGHT]; // The following uses the QR code algorithm to generate images of QR codes one by one, // The two for loops are the results of the horizontal column scan of the image. for (int y = 0; y <QR_HEIGHT; y ++) {for (int x = 0; x <QR_WIDTH; x ++) {if (bitMatrix. get (x, y) {pixels [y * QR_WIDTH + x] = 0xff000000;} else {pixels [y * QR_WIDTH + x] = 0 xffffffff ;}}} // generate the QR code image format. Use ARGB_8888 Bitmap bitmap = Bitmap. createBitmap (QR_WIDTH, QR_HEIGHT, Bitmap. config. ARGB_8888); bitmap. setPixels (pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT); // mResultImg is displayed on an ImageView. setBackground (new BitmapDrawable (bitmap); decodeBitmap (bitmap);} catch (WriterException e) {e. printStackTrace () ;}} private String decodeBitmap (Bitmap bitmap) {MultiFormatReader multiFormatReader = new MultiFormatReader (); // The decoded parameter Hashtable <DecodeHintType, Object> hints = new Hashtable <DecodeHintType, object> (2); // resolvable encoding Type Vector <BarcodeFormat> decodeFormats = new Vector <BarcodeFormat> (); if (decodeFormats = null | decodeFormats. isEmpty () {decodeFormats = new Vector <BarcodeFormat> (); // you can set the scan type here. I have selected decodeFormats. addAll (DecodeFormatManager. ONE_D_FORMATS); decodeFormats. addAll (DecodeFormatManager. QR_CODE_FORMATS); decodeFormats. addAll (DecodeFormatManager. DATA_MATRIX_FORMATS);} hints. put (DecodeHintType. POSSIBLE_FORMATS, decodeFormats); // you can specify UTF8 as the encoding format. put (DecodeHintType. CHARACTER_SET, "UTF8"); // sets the resolution Configuration Parameter multiFormatReader. setHints (hints); // start decoding image resources. try {Result rawResult = multiFormatReader. decodeWithState (new BinaryBitmap (new HybridBinarizer (new com. uperone. zxing. decoding. bitmapLuminanceSource (bitmap); mDecodeReslutTxt. setText (new StringBuilder (). append ("includes content :"). append (rawResult. getText ()). append ("\ n encoding method :"). append (rawResult. getBarcodeFormat ()). toString ();} catch (NotFoundException e) {e. printStackTrace ();} return null ;}


(2) parse the content carried in the QR Code as follows:

/**   * Decode the data within the viewfinder rectangle, and time how long it took. For efficiency,   * reuse the same reader objects from one decode to the next.   *   * @param data   The YUV preview frame.   * @param width  The width of the preview frame.   * @param height The height of the preview frame.   */  private void decode(byte[] data, int width, int height) {    long start = System.currentTimeMillis();    Result rawResult = null;    PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(data, width, height);    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));    try {      rawResult = multiFormatReader.decodeWithState(bitmap);    } catch (ReaderException re) {      // continue    } finally {      multiFormatReader.reset();    }    if (rawResult != null) {      long end = System.currentTimeMillis();      Log.d(TAG, "Found barcode (" + (end - start) + " ms):\n" + rawResult.toString());      Message message = Message.obtain(activity.getHandler(), R.id.decode_succeeded, rawResult);      Bundle bundle = new Bundle();      bundle.putParcelable(DecodeThread.BARCODE_BITMAP, source.renderCroppedGreyscaleBitmap());      message.setData(bundle);      //Log.d(TAG, "Sending decode succeeded message...");      message.sendToTarget();    } else {      Message message = Message.obtain(activity.getHandler(), R.id.decode_failed);      message.sendToTarget();    }  }

@Override  public void handleMessage(Message message) {    switch (message.what) {      case R.id.auto_focus:        //Log.d(TAG, "Got auto-focus message");        // When one auto focus pass finishes, start another. This is the closest thing to        // continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.        if (state == State.PREVIEW) {          CameraManager.get().requestAutoFocus(this, R.id.auto_focus);        }        break;      case R.id.restart_preview:        Log.d(TAG, "Got restart preview message");        restartPreviewAndDecode();        break;      case R.id.decode_succeeded:        Log.d(TAG, "Got decode succeeded message");        state = State.SUCCESS;        Bundle bundle = message.getData();        Bitmap barcode = bundle == null ? null :            (Bitmap) bundle.getParcelable(DecodeThread.BARCODE_BITMAP);        activity.handleDecode((Result) message.obj, barcode);        break;      case R.id.decode_failed:        // We're decoding as fast as possible, so when one decode fails, start another.        state = State.PREVIEW;        CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);        break;      case R.id.return_scan_result:        Log.d(TAG, "Got return scan result message");        activity.setResult(Activity.RESULT_OK, (Intent) message.obj);        activity.finish();        break;      case R.id.launch_product_query:        Log.d(TAG, "Got product query message");        String url = (String) message.obj;        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);        activity.startActivity(intent);        break;    }  }

public void handleDecode(final Result obj, Bitmap barcode){inactivityTimer.onActivity();playBeepSoundAndVibrate();String result = obj.getText();if(!TextUtils.isEmpty( result ) ){System.out.println( "result == " + result );String[] results = result.split( "#" );String user = results[ 0 ];String password = results[ 1 ];int type = Integer.parseInt( results[ 2 ] );WifiAdmin wifiAdmin = new WifiAdmin(this);          wifiAdmin.openWifi();          wifiAdmin.addNetwork(wifiAdmin.CreateWifiInfo(user, password, type));                Toast.makeText( this, result, Toast.LENGTH_LONG ).show( );}}

In this example, the camera function is used when scanning the QR code, so you need to add some permissions about camera:

<uses-permission android:name="android.permission.CAMERA" >    </uses-permission>    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >    </uses-permission>    <uses-feature android:name="android.hardware.camera" />    <uses-feature android:name="android.hardware.camera.autofocus" />    <uses-permission android:name="android.permission.VIBRATE" />    <uses-permission android:name="android.permission.FLASHLIGHT" />


For details about the demo functions and detailed code of each function, you can download the demo experience here.


How to Use the QR code of zxing to encode the code (such as A, B, C) into A QR code

Www.apkbus.com/..139981
Here is a QR code generation and identification tutorial shared by a netizen. It is accompanied by a Demo. Let's take a look at it and hope it will help you! Hope to adopt it!

Zxing can be used for the QR code client developed by ourselves

I'm afraid no one will talk to you about the QR code you have solved! I have to pay for it now.
 

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.