Android,如何在我的应用程序中读取二维码?

在我的应用程序中,我需要读取二维码。我搜索了网络,发现 Zing 代码,然而很多开发人员使用它有问题,它似乎是错误的!

如果我假设我的客户在他们的设备上安装了 qr 阅读器,那么我如何使用这些应用程序并通过隐含意图调用它们呢?

如果用户没有任何 qr 阅读器,应用程序会发生什么?如果它崩溃,我可以要求用户下载,例如 QrDroid,然后使用它吗?

185599 次浏览

使用像 ZXing 这样的 QR 库... ... 我有很好的使用经验,QrDroid 更让人头疼。如果你必须依赖外部阅读器,那就依赖像谷歌护目镜这样的标准阅读器吧!

try {


Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes


startActivityForResult(intent, 0);


} catch (Exception e) {


Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW,marketUri);
startActivity(marketIntent);


}

以及 onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {


if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
}
if(resultCode == RESULT_CANCELED){
//handle cancel
}
}
}

我已经创建了一个简单的示例教程。您可以阅读这个并在应用程序中使用。

Http://ribinsandroidhelper.blogspot.in/2013/03/qr-code-reading-on-your-application.html

通过这个链接,您可以下载 qrcode 库项目,并将其导入到工作区中,然后将库添加到项目中

把这个代码复制到你的活动中

 Intent intent = new Intent("com.google.zxing.client.android.SCAN");
startActivityForResult(intent, 0);


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
}
}
}

如果用户没有任何 qr 阅读器,应用程序会发生什么?如果它崩溃,我可以要求用户下载,例如 QrDroid,然后使用它吗?

有趣的是,谷歌现在推出的 流动视觉应用程式介面,他们都集成在播放服务本身。

在你的格拉德尔文件中只需添加:

compile 'com.google.android.gms:play-services-vision:11.4.0'

从这张 二维码教程上拍的。

更新2020:

现在二维码扫描也是机器学习工具包的一部分,所以你可以把这个模型捆绑在应用程序中,并通过集成以下级别依赖来使用它:

dependencies {
// ...
// Use this dependency to bundle the model with your app
implementation 'com.google.mlkit:barcode-scanning:16.0.3'
}

或者你可以使用下面的等级依赖从 Google Play Services 动态下载模型:

dependencies {
// ...
// Use this dependency to use the dynamically downloaded model in Google Play Services
implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:16.1.2'
}

取自 这个链接

Zxing 是一个优秀的 Qr 码扫描和生成库。 下面的实现使用 Zxing 库扫描 QR 代码图像,不要忘记在 build.gradle 中添加以下依赖项

implementation 'me.dm7.barcodescanner:zxing:1.9'

代码扫描器活动:

    public class QrCodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;


@Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Programmatically initialize the scanner view
mScannerView = new ZXingScannerView(this);
// Set the scanner view as the content view
setContentView(mScannerView);
}


@Override
public void onResume() {
super.onResume();
// Register ourselves as a handler for scan results.
mScannerView.setResultHandler(this);
// Start camera on resume
mScannerView.startCamera();
}


@Override
public void onPause() {
super.onPause();
// Stop camera on pause
mScannerView.stopCamera();
}


@Override
public void handleResult(Result rawResult) {
// Do something with the result here
// Prints scan results
Logger.verbose("result", rawResult.getText());
// Prints the scan format (qrcode, pdf417 etc.)
Logger.verbose("result", rawResult.getBarcodeFormat().toString());
//If you would like to resume scanning, call this method below:
//mScannerView.resumeCameraPreview(this);
Intent intent = new Intent();
intent.putExtra(AppConstants.KEY_QR_CODE, rawResult.getText());
setResult(RESULT_OK, intent);
finish();
}
}

在 android 工作室,您可以使用下面的过程来创建和读取 QR 码 和图像看起来像风箱 enter image description here

  1. 创建一个 android 工作室空项目
  2. 在 app.gradle 中添加库

    compile 'com.google.zxing:core:3.2.1'
    compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
    
  3. In activity.main xml use bellow..

     <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.enamul.qrcode.MainActivity">
    
    
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:orientation="vertical">
    
    
    
    
    <EditText
    android:id="@+id/editText"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:hint="Enter Text Here" />
    
    
    <Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_below="@+id/editText"
    android:text="Click Here TO generate qr code"
    android:textAllCaps="false"
    android:textSize="16sp" />
    
    
    
    
    <Button
    android:id="@+id/btnScan"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_below="@+id/editText"
    android:text="Scan Your QR Code"
    android:textAllCaps="false"
    android:textSize="16sp" />
    
    
    <TextView
    android:id="@+id/tv_qr_readTxt"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
    
    
    
    
    <ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_below="@+id/button"
    android:src="@android:drawable/ic_dialog_email" />
    
    
    
    
    </LinearLayout>
    
    
    </LinearLayout>
    
  4. In MainActivity you can use bellow code

    public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    Button button;
    Button btnScan;
    EditText editText;
    String EditTextValue ;
    Thread thread ;
    public final static int QRcodeWidth = 350 ;
    Bitmap bitmap ;
    
    
    TextView tv_qr_readTxt;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    
    imageView = (ImageView)findViewById(R.id.imageView);
    editText = (EditText)findViewById(R.id.editText);
    button = (Button)findViewById(R.id.button);
    btnScan = (Button)findViewById(R.id.btnScan);
    tv_qr_readTxt = (TextView) findViewById(R.id.tv_qr_readTxt);
    
    
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    
    
    
    
    
    
    if(!editText.getText().toString().isEmpty()){
    EditTextValue = editText.getText().toString();
    
    
    try {
    bitmap = TextToImageEncode(EditTextValue);
    
    
    imageView.setImageBitmap(bitmap);
    
    
    } catch (WriterException e) {
    e.printStackTrace();
    }
    }
    else{
    editText.requestFocus();
    Toast.makeText(MainActivity.this, "Please Enter Your Scanned Test" , Toast.LENGTH_LONG).show();
    }
    
    
    }
    });
    
    
    
    
    btnScan.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    
    
    IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
    integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
    integrator.setPrompt("Scan");
    integrator.setCameraId(0);
    integrator.setBeepEnabled(false);
    integrator.setBarcodeImageEnabled(false);
    integrator.initiateScan();
    
    
    }
    });
    }
    
    
    
    
    Bitmap TextToImageEncode(String Value) throws WriterException {
    BitMatrix bitMatrix;
    try {
    bitMatrix = new MultiFormatWriter().encode(
    Value,
    BarcodeFormat.DATA_MATRIX.QR_CODE,
    QRcodeWidth, QRcodeWidth, null
    );
    
    
    } catch (IllegalArgumentException Illegalargumentexception) {
    
    
    return null;
    }
    int bitMatrixWidth = bitMatrix.getWidth();
    
    
    int bitMatrixHeight = bitMatrix.getHeight();
    
    
    int[] pixels = new int[bitMatrixWidth * bitMatrixHeight];
    
    
    for (int y = 0; y < bitMatrixHeight; y++) {
    int offset = y * bitMatrixWidth;
    
    
    for (int x = 0; x < bitMatrixWidth; x++) {
    
    
    pixels[offset + x] = bitMatrix.get(x, y) ?
    getResources().getColor(R.color.QRCodeBlackColor):getResources().getColor(R.color.QRCodeWhiteColor);
    }
    }
    Bitmap bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444);
    
    
    bitmap.setPixels(pixels, 0, 350, 0, 0, bitMatrixWidth, bitMatrixHeight);
    return bitmap;
    }
    
    
    
    
    
    
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if(result != null) {
    if(result.getContents() == null) {
    Log.e("Scan*******", "Cancelled scan");
    
    
    } else {
    Log.e("Scan", "Scanned");
    
    
    tv_qr_readTxt.setText(result.getContents());
    Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
    }
    } else {
    // This is important, otherwise the result will not be passed to the fragment
    super.onActivityResult(requestCode, resultCode, data);
    }
    }
    }
    
  5. You can download full source code from GitHub. GitHub link is : https://github.com/enamul95/QRCode

简易二维码库

一个简单的 Android 简易二维码库。它非常容易使用,使用这个库遵循以下步骤。

格拉德尔:

步骤1。将它添加到存储库末尾的根 build.gradle 中:

allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}

步骤2。添加依赖项:

dependencies {
compile 'com.github.mrasif:easyqrlibrary:v1.0.0'
}

对于玛文:

步骤1. 将 JitPack 存储库添加到构建文件中:

<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>

步骤2。添加依赖项:

<dependency>
<groupId>com.github.mrasif</groupId>
<artifactId>easyqrlibrary</artifactId>
<version>v1.0.0</version>
</dependency>

对于 SBT:

步骤1. 将 JitPack 存储库添加到 build.sbt 文件:

resolvers += "jitpack" at "https://jitpack.io"

步骤2。添加依赖项:

libraryDependencies += "com.github.mrasif" % "easyqrlibrary" % "v1.0.0"

对雷宁根来说:

步骤1。将它添加到存储库末尾的 project.clj 中:

:repositories [["jitpack" "https://jitpack.io"]]

步骤2。添加依赖项:

:dependencies [[com.github.mrasif/easyqrlibrary "v1.0.0"]]

在您的布局 xml 文件中添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
tools:context=".MainActivity"
android:orientation="vertical">


<TextView
android:id="@+id/tvData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="No QR Data"/>
<Button
android:id="@+id/btnQRScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="QR Scan"/>


</LinearLayout>

把这个添加到你的 java 活动文件中:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{


TextView tvData;
Button btnQRScan;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData=findViewById(R.id.tvData);
btnQRScan=findViewById(R.id.btnQRScan);


btnQRScan.setOnClickListener(this);
}


@Override
public void onClick(View view){
switch (view.getId()){
case R.id.btnQRScan: {
Intent intent=new Intent(MainActivity.this, QRScanner.class);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);
} break;
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case EasyQR.QR_SCANNER_REQUEST: {
if (resultCode==RESULT_OK){
tvData.setText(data.getStringExtra(EasyQR.DATA));
}
} break;
}
}
}

对于定制的扫描仪屏幕,只需在启动扫描仪活动时添加这些行。

Intent intent=new Intent(MainActivity.this, QRScanner.class);
intent.putExtra(EasyQR.IS_TOOLBAR_SHOW,true);
intent.putExtra(EasyQR.TOOLBAR_DRAWABLE_ID,R.drawable.ic_audiotrack_dark);
intent.putExtra(EasyQR.TOOLBAR_TEXT,"My QR");
intent.putExtra(EasyQR.TOOLBAR_BACKGROUND_COLOR,"#0588EE");
intent.putExtra(EasyQR.TOOLBAR_TEXT_COLOR,"#FFFFFF");
intent.putExtra(EasyQR.BACKGROUND_COLOR,"#000000");
intent.putExtra(EasyQR.CAMERA_MARGIN_LEFT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_TOP,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_RIGHT,50);
intent.putExtra(EasyQR.CAMERA_MARGIN_BOTTOM,50);
startActivityForResult(intent, EasyQR.QR_SCANNER_REQUEST);

你完蛋了。 参考链接: < a href = “ https://mrasif.github.io/easyqrlibrary”rel = “ nofollow norefrer”> https://mrasif.github.io/easyqrlibrary

扩展 我知道的答案。

这是一个基于 Kotlin Google CameraX + ML Kit API 的实现。 请注意,截至2022年1月,CameraX API 的某些部分仍处于试验阶段。

先看看 代码实验室,然后再看看 开发指南,了解一下基础知识。

它是如何工作的?

启动 BarCodeScanerActivity 并从返回的活动结果中读取原始条形码值(Results T _ BARCODE _ RAW _ VALUE)。

建造,分级

dependencies {
    

implementation 'com.google.android.gms:play-services-mlkit-barcode-scanning:17.0.0'


def camerax_version = "1.0.1"
implementation "androidx.camera:camera-camera2:$camerax_version"
implementation "androidx.camera:camera-lifecycle:$camerax_version"
implementation "androidx.camera:camera-view:1.0.0-alpha32"
}

Activity _ bar _ code _ scanner. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".audit.BarCodeScannerActivity" >


<androidx.camera.view.PreviewView
android:id="@+id/view_finder"
android:layout_width="match_parent"
android:layout_height="match_parent" />




</androidx.constraintlayout.widget.ConstraintLayout>

条码扫描活动

class BarCodeScannerActivity : AppCompatActivity() {


private lateinit var viewBindings: ActivityBarCodeScannerBinding
private lateinit var cameraExecutorService: ExecutorService


@androidx.camera.core.ExperimentalGetImage
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)


viewBindings = ActivityBarCodeScannerBinding.inflate(layoutInflater)
setContentView(viewBindings.root)


cameraExecutorService = Executors.newSingleThreadExecutor()
startCamera()
}


override fun onDestroy() {
super.onDestroy()


cameraExecutorService.shutdown()
}


@androidx.camera.core.ExperimentalGetImage
private fun startCamera(){


val cameraProviderFuture = ProcessCameraProvider.getInstance(this)


cameraProviderFuture.addListener(
{
val cameraProvider = cameraProviderFuture.get()


val preview = Preview.Builder()
.build()
.also {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
it.setSurfaceProvider(viewBindings.viewFinder.surfaceProvider)
}
}


val barcodeAnalyzer = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build()
.also {
it.setAnalyzer(
cameraExecutorService,
BarCodeAnalyzer{ barcodes ->
if( barcodes.isNotEmpty() ) {


val intent = Intent()
intent.putExtra(
RESULT_BARCODE_RAW_VALUE,
barcodes.first().rawValue
)


setResult(RESULT_OK, intent)


cameraExecutorService.shutdown()


finish()
}
}
)
}


val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA


try {
cameraProvider.unbindAll()


cameraProvider.bindToLifecycle(
this,
cameraSelector,
preview,
barcodeAnalyzer
)


}
catch (e: Exception){}
},


ContextCompat.getMainExecutor(this)
)
}


companion object{
const val RESULT_BARCODE_RAW_VALUE = "barcode_raw_value"
}
}

条形码分析器

@androidx.camera.core.ExperimentalGetImage
class BarCodeAnalyzer(val onSuccess: (List<Barcode>) -> Unit): ImageAnalysis.Analyzer {


override fun analyze(imageProxy: ImageProxy) {


val mediaImage = imageProxy.image ?: return


val image = InputImage.fromMediaImage(
mediaImage,
imageProxy.imageInfo.rotationDegrees
)


val barcodeScannerOptions = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_ALL_FORMATS
)
.build()


val barcodeScanner = BarcodeScanning.getClient(barcodeScannerOptions)


barcodeScanner.process(image)
.addOnSuccessListener { barcodes ->
onSuccess(barcodes)
}


imageProxy.close()
}
}

MainActivity.kt

// ...


private val barcodeScannerLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
){ result ->


if( result.resultCode == Activity.RESULT_OK ){


val barcodeRawValue = result.data?.getStringExtra(
BarCodeScannerActivity.RESULT_BARCODE_RAW_VALUE
) ?: ""


}
}


private fun readBarcode(){
val intent = Intent(this, BarCodeScannerActivity::class.java)
barcodeScannerLauncher.launch(intent)
}