Android扫二维码

我使用了github yipianfengye的库,他集成了zxing的库
https://github.com/yipianfengye/android-zxingLibrary
1.Mainfests添加权限,震动的权限很重要,没有onActivityResult返回的data为null

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.CAMERA"/>
    <uses-permission android:name="android.permission.VIBRATE"/>

2.MainActivity

    private Button mBtnScanner;
    private TextView mTvResult;
    int REQUEST_CODE = 991;

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

    }

    private void initview() {
        mBtnScanner = (Button) findViewById(R.id.btn_scan);
        mTvResult = (TextView) findViewById(R.id.tv_result);

        mBtnScanner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ScannerActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果(在界面上显示)
            android.util.Log.i("zeyu","data:"+data);
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    android.util.Log.i("zeyu","bundle == null"+requestCode);
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(MainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }

    }

2.扫码界面ScannerActivity

public class ScannerActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scannerlayout);
        /**
         * 执行扫面Fragment的初始化操作
         */
        CaptureFragment captureFragment = new CaptureFragment();
        // 为二维码扫描界面设置定制化界面
        CodeUtils.setFragmentArgs(captureFragment, R.layout.camerlayout);

        captureFragment.setAnalyzeCallback(analyzeCallback);
        /**
         * 替换我们的扫描控件
         */
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_my_container, captureFragment).commit();
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
            bundle.putString(CodeUtils.RESULT_STRING, result);
            resultIntent.putExtras(bundle);
            ScannerActivity.this.setResult(RESULT_OK, resultIntent);
            ScannerActivity.this.finish();
        }

        @Override
        public void onAnalyzeFailed() {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
            bundle.putString(CodeUtils.RESULT_STRING, "");
            resultIntent.putExtras(bundle);
            ScannerActivity.this.setResult(RESULT_OK, resultIntent);
            ScannerActivity.this.finish();
        }
    };
}

3.MainActivity的界面:activity_main.xml

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

    <Button
        android:id="@+id/btn_scan"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="扫码"
        />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="result"
        />

</LinearLayout>

4.扫码Activity的界面:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/second_button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="10dp"
        android:layout_gravity="bottom|center_horizontal"
        />

    <FrameLayout
        android:id="@+id/fl_my_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></FrameLayout>

</FrameLayout>

5.camerlayout.xml 用于绘制扫码框样式

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <SurfaceView
        android:id="@+id/preview_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <com.uuzuche.lib_zxing.view.ViewfinderView
        android:id="@+id/viewfinder_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:inner_width="200dp"
        app:inner_height="200dp"
        app:inner_margintop="150dp"
        app:inner_corner_length="30dp"
        app:inner_corner_width="5dp"
        app:inner_scan_speed="10"
        app:inner_scan_iscircle="false"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="370dp"
        android:layout_gravity="center_horizontal"
        android:text="请扫描二维码进行登录"
        android:textColor="@color/bg_color" />

</FrameLayout>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 在Android Studio中,我们可以使用ZXing库来实现二维码描功能。 首先,我们需要在项目的build.gradle文件中添加以下依赖项: ```groovy implementation 'com.google.zxing:core:3.4.1' implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar' ``` 接下来,在我们的活动(Activity)类中,我们需要添加一个按钮和一个ImageView,用于触发描和展示描结果。 ```xml <Button android:id="@+id/scanButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="二维码" /> <ImageView android:id="@+id/qrCodeImageView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="16dp" /> ``` 然后,在我们的活动类中,我们需要添加以下代码来处理描按钮的点击事件: ```java // 找到按钮和图像视图 Button scanButton = findViewById(R.id.scanButton); ImageView qrCodeImageView = findViewById(R.id.qrCodeImageView); // 设置描按钮的点击监听器 scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE); integrator.setPrompt("请对准二维码进行描"); integrator.setCameraId(0); integrator.initiateScan(); } }); // 处理描结果 @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Toast.makeText(this, "描已取消", Toast.LENGTH_SHORT).show(); } else { String qrCodeData = result.getContents(); qrCodeImageView.setImageBitmap(QRCodeEncoder.encodeAsBitmap(qrCodeData, BarcodeFormat.QR_CODE, 400, 400)); } } else { super.onActivityResult(requestCode, resultCode, data); } } ``` 最后,我们需要添加一个辅助类QRCodeEncoder,用于将描结果转换为二维码图片: ```java public class QRCodeEncoder { public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int width, int height) throws WriterException { BitMatrix result; try { result = new MultiFormatWriter().encode(contents, format, width, height, null); } catch (IllegalArgumentException iae) { return null; } int w = result.getWidth(); int h = result.getHeight(); int[] pixels = new int[w * h]; for (int y = 0; y < h; y++) { int offset = y * w; for (int x = 0; x < w; x++) { pixels[offset + x] = result.get(x, y) ? Color.BLACK : Color.WHITE; } } Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, w, h); return bitmap; } } ``` 通过以上步骤,我们就能在Android Studio中实现二维码描功能了。当用户点击描按钮时,系统会打开相机二维码描完成后将结果展示在ImageView中。 ### 回答2: 在Android Studio中,可以使用第三方库来实现二维码码的功能。以下是实现步骤: 1. 在项目的build.gradle文件中添加以下依赖项: ``` dependencies { implementation 'com.google.zxing:core:3.3.0' implementation 'com.journeyapps:zxing-android-embedded:4.2.0' } ``` 2. 创建一个用于二维码Activity或Fragment。 ```java import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class ScanQRCodeActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private static final int PERMISSION_REQUEST_CAMERA = 1; private ZXingScannerView scannerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_qrcode); scannerView = findViewById(R.id.scanner_view); // 请求相机权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CAMERA); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == PERMISSION_REQUEST_CAMERA) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 用户允许相机权限,开始scannerView.setResultHandler(this); scannerView.startCamera(); } else { // 用户拒绝相机权限,提示并关闭Activity Toast.makeText(this, "无法使用相机,应用即将关闭", Toast.LENGTH_SHORT).show(); finish(); } } } @Override public void handleResult(Result result) { // 处理描结果 String scannedResult = result.getText(); Log.d("ScanQRCodeActivity", "Scanned Result: " + scannedResult); // 可以将描的结果返回给上一个Activity或Fragment Intent intent = new Intent(); intent.putExtra("result", scannedResult); setResult(RESULT_OK, intent); finish(); } @Override protected void onPause() { super.onPause(); // 停止相机预览 scannerView.stopCamera(); } } ``` 3. 在布局文件中添加一个ZXingScannerView。 ```xml <me.dm7.barcodescanner.zxing.ZXingScannerView android:id="@+id/scanner_view" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 现在,你可以通过启动ScanQRCodeActivity二维码描的结果将在Logcat中显示,并返回给上一个Activity或Fragment。 ### 回答3: 在Android Studio中实现二维码码功能可以通过使用Zxing库来实现。下面是具体的步骤: 1. 首先,需要在项目的`build.gradle`文件中添加Zxing库的依赖: ```groovy dependencies { implementation 'com.google.zxing:core:3.4.0' implementation 'com.journeyapps:zxing-android-embedded:4.2.0' } ``` 2. 在需要码的Activity中添加一个ImageButton作为码按钮,并在布局文件中引入Zxing的CaptureFragment用于显示码界面: ```xml <RelativeLayout 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"> <!-- 码按钮 --> <ImageButton android:id="@+id/scanButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/ic_scan" /> <!-- 码界面 --> <fragment android:id="@+id/scannerFragment" android:name="com.journeyapps.barcodescanner.CaptureFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout="@layout/capture" /> </RelativeLayout> ``` 3. 在Activity的onCreate方法中添加码按钮的点击事件,并通过Intent启动码界面: ```java import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import com.google.zxing.integration.android.IntentIntegrator; public class MainActivity extends AppCompatActivity { private ImageButton scanButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); scanButton = findViewById(R.id.scanButton); scanButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this); intentIntegrator.setBeepEnabled(false); intentIntegrator.setCaptureActivity(CaptureActivityAnyOrientation.class); intentIntegrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null && result.getContents() != null) { String qrCode = result.getContents(); // 处理描结果 } } } ``` 4. 添加一个自定义的CaptureActivity,用于实现码界面自动旋转的功能: ```java import com.journeyapps.barcodescanner.CaptureActivity; public class CaptureActivityAnyOrientation extends CaptureActivity { // 空实现 } ``` 使用以上步骤,就可以在Android Studio中实现二维码码功能了。当点击码按钮时,会打开一个码界面,描成功后会返回描结果,你可以根据需要进行后续的处理。如果需要进一步定制码界面的样式,可以参考Zxing库的官方文档进行自定义。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值