在我的应用程序中,我需要阅读Qr代码。我在网上搜索并找到了Zing代码,但是许多开发人员在使用它时遇到了问题,而且似乎有问题!
如果我假设我的客户在其设备上安装了QR阅读器,那么我该如何使用这些应用程序并通过隐式意图对其进行调用?
如果用户没有任何QR阅读器,应用程序将如何处理?如果崩溃,我可以要求用户下载例如QrDroid,然后再使用它吗?
Answers:
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
}
}
}
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();
}
}
如果用户没有任何QR阅读器,应用程序将如何处理?如果崩溃,我可以要求用户下载例如QrDroid,然后再使用它吗?
有趣的是,Google现在推出了Mobile Vision API,它们已集成到播放服务本身中。
在您的Gradle文件中添加:
compile 'com.google.android.gms:play-services-vision:11.4.0'
摘自此QR代码教程。
2020年更新:
现在,QR码扫描也是ML Kit的一部分,因此您可以将模型捆绑在应用程序内,并通过集成以下gradle依赖项来使用它:
dependencies {
// ...
// Use this dependency to bundle the model with your app
implementation 'com.google.mlkit:barcode-scanning:16.0.3'
}
或者,您可以使用以下gradle依赖性从Google Play服务动态下载模型:
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'
}
取自此链接。
在android studio中,您可以使用波纹管处理来创建和读取QR代码, 并使其看起来像波纹
在app.gradle中添加库
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
在activity.main 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"
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>
在MainActivity中,您可以使用以下代码
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);
}
}
}
您可以从GitHub下载完整的源代码。GitHub链接是:https : //github.com/enamul95/QRCode
我创建了一个简单的示例教程。您可以阅读并在您的应用程序中使用。
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
}
}
}
一个简单的Android Easy QR代码库。它很容易使用,按照以下步骤使用该库。
步骤1.将其添加到存储库末尾的root 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>
步骤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 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>
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);
大功告成 参考 链接:https://mrasif.github.io/easyqrlibrary