How to implement QR code scanner in Fragment in portrait mode in android?

巧了我就是萌 提交于 2019-11-29 11:57:06

Use this Library for QR code scanner it is the Modification of ZXING Scanner project for easy Android QR-Code detection.QR Code Scanner

Prakhar1001

For Android Studio Users

repositories {
 maven {
            url "https://jitpack.io"
    }
 }

compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'

First of all, you need to to trigger an intent by virtue of which camera gets open (Scanner).

Intent intent = new Intent("com.google.zxing.client.android.SCAN");                
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");

Then , If trigerred within a Fragment then write, else you will get your request code wrong.

getActivity().startActivityForResult(intent, 0);

If From Activity

startActivityForResult(intent, 0);

Then, it must be an Activity where you need your results captured by the scanner, I have captured and thus displayed in a Toast.

 public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
              Toast.makeText(this,contents,Toast.LENGTH_LONG).show();
                // Handle successful scan
            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
            }
        }
    }

Finally, Index it in manifest File, Use of intent filters enables it to recognise its source and function

<activity android:name="com.journeyapps.barcodescanner.CaptureActivity"
        android:clearTaskOnLaunch="true"
        android:stateNotNeeded="true">
        <intent-filter>
            <action android:name="com.google.zxing.client.android.SCAN"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!