Android识别图片中的WIFI二维码,并自动连接

 

原理:扫描或识别图片中的二维码后,解析其内容,打开WiFi管理器,加入此WiFi。

 

实现步骤:

1.导入依赖库;

2.封装识别指定路径下二维码图片的方法;

3.获取WiFi的账号密码

4.打开WiFi管理器,连接此WiFi

 

1.导入依赖库

implementation 'com.google.zxing:core:3.2.1'
implementation 'cn.bingoogolapple:bga-qrcodecore:1.1.7@aar'
implementation 'cn.bingoogolapple:bga-zxing:1.1.7@aar'

 

2.封装识别指定路径下二维码图片的方法;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
​
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.GlobalHistogramBinarizer;
import com.google.zxing.common.HybridBinarizer;
​
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
​
public class QRCodeUtil {
​
    private static final String TAG = "QRCodeUtil";
​
    private static final Map<DecodeHintType, Object> HINTS = new EnumMap<>(DecodeHintType.class);
​
    static {
        List<BarcodeFormat> allFormats = new ArrayList<>();
        allFormats.add(BarcodeFormat.AZTEC);
        allFormats.add(BarcodeFormat.CODABAR);
        allFormats.add(BarcodeFormat.CODE_39);
        allFormats.add(BarcodeFormat.CODE_93);
        allFormats.add(BarcodeFormat.CODE_128);
        allFormats.add(BarcodeFormat.DATA_MATRIX);
        allFormats.add(BarcodeFormat.EAN_8);
        allFormats.add(BarcodeFormat.EAN_13);
        allFormats.add(BarcodeFormat.ITF);
        allFormats.add(BarcodeFormat.MAXICODE);
        allFormats.add(BarcodeFormat.PDF_417);
        allFormats.add(BarcodeFormat.QR_CODE);
        allFormats.add(BarcodeFormat.RSS_14);
        allFormats.add(BarcodeFormat.RSS_EXPANDED);
        allFormats.add(BarcodeFormat.UPC_A);
        allFormats.add(BarcodeFormat.UPC_E);
        allFormats.add(BarcodeFormat.UPC_EAN_EXTENSION);
        HINTS.put(DecodeHintType.TRY_HARDER, BarcodeFormat.QR_CODE);
        HINTS.put(DecodeHintType.POSSIBLE_FORMATS, allFormats);
        HINTS.put(DecodeHintType.CHARACTER_SET, "utf-8");
    }
​
    /**
     * 同步解析本地图片二维码。该方法是耗时操作,请在子线程中调用。
     *
     * @param picturePath 要解析的二维码图片本地路径
     * @return 返回二维码图片里的内容 或 null
     */
    public static String syncDecodeQRCode(String picturePath) {
        return syncDecodeQRCode(getDecodeAbleBitmap(picturePath));
    }
​
    /**
     * 同步解析bitmap二维码。该方法是耗时操作,请在子线程中调用。
     *
     * @param bitmap 要解析的二维码图片
     * @return 返回二维码图片里的内容 或 null
     */
    private static String syncDecodeQRCode(Bitmap bitmap) {
        Result result = null;
        RGBLuminanceSource source = null;
        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int[] pixels = new int[width * height];
            bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
            source = new RGBLuminanceSource(width, height, pixels);
            result = new MultiFormatReader()
                    .decode(new BinaryBitmap(new HybridBinarizer(source)), HINTS);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
            if (source != null) {
                try {
                    result = new MultiFormatReader()
                            .decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)), HINTS);
                    return result.getText();
                } catch (Throwable e2) {
                    e2.printStackTrace();
                }
            }
            return null;
        }
    }
​
    /**
     * 将本地图片文件转换成可解码二维码的 Bitmap。为了避免图片太大,这里对图片进行了压缩。
     * 感谢 https://github.com/devilsen 提的 PR
     *
     * @param picturePath 本地图片文件路径
     * @return
     */
    private static Bitmap getDecodeAbleBitmap(String picturePath) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(picturePath, options);
            int sampleSize = options.outHeight / 400;
            if (sampleSize <= 0) {
                sampleSize = 1;
            }
            options.inSampleSize = sampleSize;
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeFile(picturePath, options);
        } catch (Exception e) {
            return null;
        }
    }
​
}

 

3.获取WiFi的账号和密码。

调用第2步中封装的识别图片二维码的方法

String strResult = QRCodeUtil.syncDecodeQRCode("/storage/emulated/0/test.png");
Log.d(TAG, "result: " + strResult);

字符串分割,获取网络名,密码及网络类型。

String netWorkNameTemp = strResult.substring(strResult.indexOf("S:"));
netWorkName = netWorkNameTemp.substring(3, netWorkNameTemp.indexOf(";") - 1);
String netWorkTypeTemp = strResult.substring(strResult.indexOf("T:"));
netWorkType = netWorkTypeTemp.substring(2, netWorkTypeTemp.indexOf(";"));
String passwordTemp = strResult.substring(strResult.indexOf("P:"));
password = passwordTemp.substring(3, passwordTemp.indexOf(";") - 1);
Log.i(TAG, "netWorkName: " + netWorkName + " netWorkType: " + netWorkType + " password: " + password);

4.打开WiFi管理器,连接此WiFi

if (!wifiAdmin.mWifiManager.isWifiEnabled()) {
     wifiAdmin.openWifi();
}
int netType;
if (netWorkType.compareToIgnoreCase("wpa") == 0) {
    netType = WifiAdmin.TYPE_WPA;
} else if (netWorkType.compareToIgnoreCase("wep") == 0) {
    netType = WifiAdmin.TYPE_WEP;
} else {
    netType = WifiAdmin.TYPE_NO_PWD;
}
wifiAdmin.addNetwork(netWorkName, password, netType);

 

5.参考

https://www.jianshu.com/p/14ce26f5a5c7

https://blog.csdn.net/android_cmos/article/details/52214560

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Android 平台上可以使用 Google 提供的移动视觉技术库(Mobile Vision API)来实现二维码识别功能。具体步骤如下: 1. 在 build.gradle 文件添加以下依赖: ```groovy implementation 'com.google.android.gms:play-services-vision:20.1.3' ``` 2. 在布局文件添加一个 SurfaceView,用于相机预览。 3. 在 Activity 获取 SurfaceView 对象,并创建相机预览视图。 ```java // 获取 SurfaceView 对象 SurfaceView surfaceView = findViewById(R.id.surfaceView); // 创建相机预览视图 CameraSource cameraSource = new CameraSource.Builder(context, barcodeDetector) .setAutoFocusEnabled(true) .build(); SurfaceHolder holder = surfaceView.getHolder(); holder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { try { cameraSource.start(holder); // 启动相机预览 } catch (IOException e) { e.printStackTrace(); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // 不需要实现 } @Override public void surfaceDestroyed(SurfaceHolder holder) { cameraSource.stop(); // 停止相机预览 } }); ``` 4. 创建一个 BarcodeDetector 对象,并将其与相机预览视图关联起来。 ```java // 创建一个 BarcodeDetector 对象 BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context) .setBarcodeFormats(Barcode.QR_CODE) .build(); // 将 BarcodeDetector 与相机预览视图关联起来 cameraSource.setPreviewCallback(barcodeDetector); barcodeDetector.setProcessor(new Detector.Processor<Barcode>() { @Override public void release() { // 不需要实现 } @Override public void receiveDetections(Detector.Detections<Barcode> detections) { SparseArray<Barcode> qrCodes = detections.getDetectedItems(); if (qrCodes.size() != 0) { String qrCodeValue = qrCodes.valueAt(0).displayValue; Log.d("QRCode", "QR Code value: " + qrCodeValue); // 在这里处理识别出的二维码数据 } } }); ``` 至此,二维码识别功能就实现了。当用户将二维码放入相机预览视图时,程序会自动识别二维码,并将其显示在 Logcat 。你可以在 `receiveDetections` 方法添加自己的逻辑来处理识别出的二维码数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值