美文网首页
第十三章

第十三章

作者: 贤兵 | 来源:发表于2020-12-21 00:01 被阅读0次

    一、ZXing

    ZXing ("zebra crossing") is an open-source, multi-format 1D/2D barcode image processing library implemented in Java, with ports to other languages.
    https://github.com/zxing/zxing

    android-zxingLibrary 几行代码快速集成二维码扫描功能
    https://github.com/yipianfengye/android-zxingLibrary
    可打开默认二维码扫描页面
    支持对图片Bitmap的扫描功能
    支持对UI的定制化操作
    支持对条形码的扫描功能
    支持生成二维码操作
    支持控制闪光灯开关

    1、拍摄识别二维码

    1.依赖

    compile 'cn.yipianfengye.android:zxing-library:2.2'
    

    2.权限

        <uses-permission android:name="android.permission.CAMERA"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <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.WAKE_LOCK" />
        <uses-permission android:name="android.permission.INTERNET" />
    

    3.初始化

    public class App extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            ZXingLibrary.initDisplayOpinion(this);
        }
    }
    

    4.mainfest中配置app

        <application
            android:name=".App"
    

    5.拍摄二维码进行识别

    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
    startActivityForResult(intent, REQUEST_CODE);
    

    6.扫描结果

        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQ_CODE) {
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            int type = bundle.getInt(CodeUtils.RESULT_TYPE);
                            if (type == CodeUtils.RESULT_SUCCESS) {
                                String str = bundle.getString(CodeUtils.RESULT_STRING);
                                Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }
        }
    

    2、解析手机本地二维码

    1.依赖

    如上

    2.权限

    如上

    3.初始化

    如上

    4.mainfest中配置app.

    如上

    5.manifest中app新加

    android:requestLegacyExternalStorage="true"
    

    6.选取图片

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("image/*");
    startActivityForResult(intent, REQUEST_IMAGE);
    

    7.扫描结果

                if (requestCode == REQUEST_IMAGE) {
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri uri = data.getData();
                        String path = FileUtil.getFilePathByUri(getApplicationContext(), uri);
                        CodeUtils.analyzeBitmap(path, new CodeUtils.AnalyzeCallback() {
                            @Override
                            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                                Toast.makeText(MainActivity.this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                            }
    
                            @Override
                            public void onAnalyzeFailed() {
                                Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }
    

    FileUtil.java

    public class FileUtil {
        public static String getFilePathByUri(Context context, Uri uri) {
            if ("content".equalsIgnoreCase(uri.getScheme())) {
                int sdkVersion = Build.VERSION.SDK_INT;
                if (sdkVersion >= 19) {
                    return getRealPathFromUriAboveApi19(context, uri);
                }
            }
            return null;
        }
    
        @SuppressLint("NewApi")
        private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
            String filePath = null;
            if (DocumentsContract.isDocumentUri(context, uri)) {
                // 如果是document类型的 uri, 则通过document id来进行处理
                String documentId = DocumentsContract.getDocumentId(uri);
                if (isMediaDocument(uri)) { // MediaProvider
                    // 使用':'分割
                    String type = documentId.split(":")[0];
                    String id = documentId.split(":")[1];
    
                    String selection = MediaStore.Images.Media._ID + "=?";
                    String[] selectionArgs = {id};
    
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
    
                    filePath = getDataColumn(context, contentUri, selection, selectionArgs);
                }
            }
            return filePath;
        }
    
        private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
            String path = null;
    
            String[] projection = new String[]{MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                    path = cursor.getString(columnIndex);
                }
            } catch (Exception e) {
                if (cursor != null) {
                    cursor.close();
                }
            }
            return path;
        }
    
        private static boolean isMediaDocument(Uri uri) {
            return "com.android.providers.media.documents".equals(uri.getAuthority());
        }
    }
    

    3、生成二维码

    1.准备工作

    如上

    2.

        private void generateErWeiMa() {
            String str = "wangxianbing";
            ImageView imageView = findViewById(R.id.image_view);
    //        Bitmap mBitmap = CodeUtils.createImage(str, 400, 400, null);
            Bitmap mBitmap = CodeUtils.createImage(str, 400, 400, BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher));
            imageView.setImageBitmap(mBitmap);
        }
    

    二、LeakCanary

    LeakCanary is a memory leak detection library for Android.
    https://github.com/square/leakcanary

    LeakCanary automatically detects leaks of the following objects:
    -destroyed Activity instances
    -destroyed Fragment instances
    -destroyed fragment View instances
    -cleared ViewModel instances

    1.依赖

    debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.5'
    

    2.在第一个activity中添加点击事件,点击按钮后打开第二个activity

    3.新建一个管理类,模拟管擦着模式

    public class Manager {
    private static Manager sManager = new Manager();
    private Manager(){}
    public static Manager getInstance() {
    return sManager;
    }
    List<Callback> mList = new ArrayList<>();
    public void register(Callback callback) {
    mList.add(callback);
    }
    public void unregister(Callback callback) {
    mList.remove(callback);
    }
    public static interface Callback {}
    }

    4.在第二个Activity的onCreate中调用Manager.getInstance().register(this);

    5.连续几次打开第二个Activity,查看LeakCanary

    图片.png

    相关文章

      网友评论

          本文标题:第十三章

          本文链接:https://www.haomeiwen.com/subject/nsklnktx.html