How to scan QRCode in android

前端 未结 7 2321
说谎
说谎 2020-12-25 14:04

I found a tutorial on how to scan a barcode. But in my application I have to scan a QR code. How can I a scan QR code in Android?

7条回答
  •  抹茶落季
    2020-12-25 15:00

    Here is the function that scans the QR Code.

    public void scanQR(View v)
    {
        try
        {
            Intent intent = new Intent(ACTION_SCAN);
            intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
            startActivityForResult(intent, 0);
        }
        catch (ActivityNotFoundException anfe)
        {
            showDialog(ActivityUserDetails.this, "No Scanner Found",
                    "Download a scanner code activity?", "Yes", "No").show();
        }
    }
    

    In the above code snippet, I have invoked showDialog() method from catch block, that will show an AlertDialog for asking to install "Barcode Scanner" app from Google Play. Given below is the code for showDialog method.

    private static AlertDialog showDialog(final Activity act,
                                          CharSequence title, CharSequence message, CharSequence buttonYes,
                                          CharSequence buttonNo)
    {
        AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
        downloadDialog.setTitle(title);
        downloadDialog.setMessage(message);
        downloadDialog.setPositiveButton(buttonYes,
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                        Uri uri = Uri.parse("market://search?q=pname:"
                                + "com.google.zxing.client.android");
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        try
                        {
                            act.startActivity(intent);
                        }
                        catch (ActivityNotFoundException anfe)
                        {
    
                        }
                    }
                });
                downloadDialog.setNegativeButton(buttonNo,
                new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialogInterface, int i)
                    {
                    }
                });
                return downloadDialog.show();
    }
    

    I have used this function on Button click event. Therefore the code for Button is given below (xml file).

                        

    NOTE: The prerequisite for using this function is that you must have pre installed "Barcode Scanner" app in your device.

    Hope it helps.

    Thanks :)

提交回复
热议问题