启动应用程序后如何立即启动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扫描仪,然后显示扫描详细信息?它是否需要新的活动?

我使用ZSING库来实现扫描程序。

谢谢!

使用您的代码,您可以通过两种方式启动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)

}

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

buttonScan!!.callOnClick

最新更新