You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中实现手机端二维码扫描功能

Step-by-Step Guide to Implement QR Code Scanning in Android Studio

Hey there, let's walk through how to get that QR scan functionality up and running with your existing setup. I'll assume you already have the basic activity structure in place, so let's dive in:

1. Double-Check Dependencies (If Needed)

Even though you mentioned having the ZXing classes imported, make sure your app-level build.gradle (Module level) includes the zxing-android-embedded dependency to avoid runtime issues:

dependencies {
    // ZXing QR Scanner
    implementation 'com.journeyapps:zxing-android-embedded:4.3.0'
    implementation 'com.google.zxing:core:3.4.1'
}

Sync your project after adding these to ensure everything links properly.

2. Configure Your Layout (res/layout/activity_qrscan.xml)

You mentioned having a scan button and text display—here's a simple example layout that matches your setup:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center">

    <Button
        android:id="@+id/btn_scan_qr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Scan QR Code"/>

    <TextView
        android:id="@+id/tv_scanned_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:marginTop="24dp"
        android:textSize="18sp"
        android:hint="Scanned result will appear here"/>

</LinearLayout>

3. Implement the Scan Trigger in Your qrscan Activity

In your qrscan.java file, set up the button click listener to launch the ZXing scanner. We'll use IntentIntegrator which simplifies the process:

First, declare your UI elements and set up the listener:

public class qrscan extends AppCompatActivity {
    private Button btnScan;
    private TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrscan);

        btnScan = findViewById(R.id.btn_scan_qr);
        tvResult = findViewById(R.id.tv_scanned_result);

        // Set click listener for scan button
        btnScan.setOnClickListener(v -> {
            // Check camera permission first
            if (ContextCompat.checkSelfPermission(qrscan.this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                // Request camera permission if not granted
                ActivityCompat.requestPermissions(qrscan.this,
                        new String[]{Manifest.permission.CAMERA},
                        100);
            } else {
                // Launch QR scanner
                startQRScanner();
            }
        });
    }
}

Then add the startQRScanner() method to configure and launch the scanner:

private void startQRScanner() {
    IntentIntegrator integrator = new IntentIntegrator(this);
    integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
    integrator.setPrompt("Scan a QR Code");
    integrator.setCameraId(0); // Use rear camera
    integrator.setBeepEnabled(true);
    integrator.setBarcodeImageEnabled(true);
    integrator.initiateScan();
}

4. Handle the Scan Result

For Android 9 (API 28) and below:

Override onActivityResult to capture the scan result:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() == null) {
            tvResult.setText("Scan cancelled");
        } else {
            String scannedData = result.getContents();
            tvResult.setText("Scanned Data: " + scannedData);
            
            // Optional: Encrypt the scanned data using AES (if needed)
            String encryptedData = encryptAES(scannedData);
            // Display or store encryptedData as required
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

For Android 10+ (API 29+):

Use registerForActivityResult (recommended for newer versions) instead of overriding onActivityResult:
Add this inside your onCreate method:

ActivityResultLauncher<Intent> scanLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            IntentResult scanResult = IntentIntegrator.parseActivityResult(
                    result.getResultCode(), result.getData());
            if (scanResult != null) {
                if (scanResult.getContents() == null) {
                    tvResult.setText("Scan cancelled");
                } else {
                    String scannedData = scanResult.getContents();
                    tvResult.setText("Scanned Data: " + scannedData);
                    
                    // Optional: AES encryption here
                    String encryptedData = encryptAES(scannedData);
                    // Do something with encryptedData
                }
            }
        });

// Update startQRScanner() to use the launcher:
private void startQRScanner() {
    IntentIntegrator integrator = new IntentIntegrator(this);
    integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE);
    integrator.setPrompt("Scan a QR Code");
    integrator.setCameraId(0);
    integrator.setBeepEnabled(true);
    integrator.setBarcodeImageEnabled(true);
    scanLauncher.launch(integrator.createScanIntent());
}

5. Implement AES Encryption (Optional)

Since you mentioned having AES-related classes, here's a sample encryptAES method you can use (adjust the key and IV according to your requirements):

private String encryptAES(String plainText) {
    try {
        // Replace with your own secret key (16, 24, or 32 bytes for AES-128, 192, 256)
        String secretKey = "YourSecretKey123";
        byte[] key = MessageDigest.getInstance("SHA-256").digest(secretKey.getBytes(StandardCharsets.UTF_8));
        key = Arrays.copyOf(key, 16); // Use first 16 bytes for AES-128

        // Initialization Vector (IV)
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivSpec);

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        
        // Combine IV and encrypted data (IV is needed for decryption later)
        byte[] combined = new byte[iv.length + encryptedBytes.length];
        System.arraycopy(iv, 0, combined, 0, iv.length);
        System.arraycopy(encryptedBytes, 0, combined, iv.length, encryptedBytes.length);
        
        return Base64.encodeToString(combined, Base64.DEFAULT);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

6. Handle Camera Permissions

Add the camera permission to your AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="true"/>

Then handle the permission request result:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startQRScanner();
        } else {
            Toast.makeText(this, "Camera permission is required to scan QR codes", Toast.LENGTH_SHORT).show();
        }
    }
}

That's it! Your QR scanning functionality should now work. Test it with a sample QR code to ensure everything flows correctly—scanning will display the result in your text view, and you can optionally encrypt the data if you enabled that step.

内容的提问来源于stack exchange,提问作者Raj K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:57:28