Android实现二维码扫描功能

首先,需要添加依赖

compile 'com.mylhyl:zxingscanner:1.6.0'

 

接着,就是xml布局,很简单,两个类

   MainActivity布局(第一个类布局)



    

   SecondActivity布局(第二个类布局)



    

    

 

 接着,就是代码实现扫描,很简单,有注释,直接上代码

  MainActivity类(第一个类的代码)

public class MainActivity extends AppCompatActivity {

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

        //点击跳转到二维码扫描页面
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivityForResult(intent,100);
            }
        });

    }

    //回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == 200){
            //通过回调得到扫描后的值
            String text = data.getStringExtra("text");
            Toast.makeText(MainActivity.this,"扫描成功",Toast.LENGTH_SHORT).show();
        }

    }
}

 

  SecondActivity (第二个类的代码)

 

public class SecondActivity extends AppCompatActivity {

    private ScannerView mScannerView;

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

        mScannerView = (ScannerView) findViewById(R.id.scanner_view);

        mScannerView.setOnScannerCompletionListener(new OnScannerCompletionListener() {
            @Override
            public void OnScannerCompletion(Result rawResult, ParsedResult parsedResult, Bitmap barcode) {

                //获取扫描后得到的值
                String text = rawResult.getText();

                //传递扫描得到的值
                Intent intent = new Intent();
                intent.putExtra("text",text);
                setResult(200,intent);

                finish();

            }
        });

    }

    @Override
    protected void onResume() {
        mScannerView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mScannerView.onPause();
        super.onPause();
    }

}

 

 

 

最后,不要忘记添加权限



 

 

 

备注:像小米或华为的部分手机扫描之后黑屏,需要动态添加权限

//开启手机里的相机权限,安卓6.0以后的系统需要,否则会报错
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {
    //申请WRITE_EXTERNAL_STORAGE权限
    ActivityCompat.requestPermissions(MainActivity.this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
            1);
}

 

 

 

 

 

 

你可能感兴趣的:(Android实现二维码扫描功能)