如何在启动应用程序后立即启动QR扫描仪?

时间:2018-10-20 13:24:12

标签: android qr-code

我的QR码扫描代码如下:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //View objects
        buttonScan = findViewById<View>(R.id.buttonScan) as Button
        textViewName = findViewById<View>(R.id.textViewName) as TextView
        textViewAddress = findViewById<View>(R.id.textViewAddress) as TextView

        //intializing scan object
        qrScan = IntentIntegrator(this)

        //attaching onclick listener
        buttonScan!!.setOnClickListener(this)


    }

    //Getting the scan results
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            //if qrcode has nothing in it
            if (result.contents == null) {
                Toast.makeText(this, "Result Not Found", Toast.LENGTH_LONG).show()
            } else {
                //if qr contains data
                try {

                    //converting the data to json
                    val obj = JSONObject(result.contents)
                    //setting values to textviews
                    textViewName!!.text = obj.getString("busno")

                    textViewAddress!!.text = obj.getString("busname")


                } catch (e: JSONException) {
                    e.printStackTrace()
                    //if control comes here
                    //that means the encoded format not matches
                    //in this case you can display whatever data is available on the qrcode
                    //to a toast
                    Toast.makeText(this, result.contents, Toast.LENGTH_LONG).show()
                }

            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

    override fun onClick(view: View) {
        //initiating the qr code scan
        qrScan!!.initiateScan()
    }

按下我声明为buttonScan的按钮后,QR码扫描器启动。打开应用程序后如何立即启动QR扫描仪,然后显示扫描详细信息?是否需要新的活动?

我已使用ZXING库实现扫描仪。

谢谢!

1 个答案:

答案 0 :(得分:1)

使用您的代码,您可以通过两种方式启动QR扫描仪:

第一种方法是在qrScan = IntentIntegrator(this)

之后立即启动扫描

因此您的onCreate可以是:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //View objects
        buttonScan = findViewById<View>(R.id.buttonScan) as Button
        textViewName = findViewById<View>(R.id.textViewName) as TextView
        textViewAddress = findViewById<View>(R.id.textViewAddress) as TextView

        //intializing scan object
        qrScan = IntentIntegrator(this)

        //initiate scan directly
        qrScan!!.initiateScan()

        //attaching onclick listener
        buttonScan!!.setOnClickListener(this)


    }

第二种方法是将click事件触发到buttonScan,它将直接启动扫描。

buttonScan!!.callOnClick