📜  如何在Android中生成QR码?

📅  最后修改于: 2021-05-09 16:37:10             🧑  作者: Mango

QR码在许多应用程序中用于以机器可读形式显示数据。这些代码用于以安全的方式表示数据,该数据只能由机器读取,而不能由人类读取。我们已经看到许多提供QR码的应用程序,我们可以使用我们的移动设备扫描QR码。在本文中,我们将研究如何为我们的应用程序生成QR码。因此,为了实现此功能,我们将使用来自GitHub的库。

QR Code Generator在Android中的实现

我们将创建一个简单的QR Code生成器应用程序,在该应用程序中,我们将从该应用程序添加数据并生成一个QR Code,该QR Code将在其中显示数据。下面是示例GIF,您将在其中基本了解我们将在本文中进行的工作。并不是说我们使用Java语言来构建此项目。

在Android示例GIF中生成QR码

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将依赖项添加到build.gradle(Module:app)

导航到Gradle脚本> build.gradle(Module:app)并将以下依赖项添加到“依赖项”部分。

现在,从立即同步的右上角选项同步项目。

步骤3:修改字符串.xml文件

以下是字符串.xml文件的代码。

XML

    GFG App
    qr_code
    Enter your info
    Generate QR Code


XML


  
    
    
  
    
    
  
    
    


Java
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.WriterException;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
  
public class MainActivity extends AppCompatActivity {
  
    // variables for imageview, edittext,
    // button, bitmap and qrencoder.
    private ImageView qrCodeIV;
    private EditText dataEdt;
    private Button generateQrBtn;
    Bitmap bitmap;
    QRGEncoder qrgEncoder;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all variables.
        qrCodeIV = findViewById(R.id.idIVQrcode);
        dataEdt = findViewById(R.id.idEdt);
        generateQrBtn = findViewById(R.id.idBtnGenerateQR);
  
        // initializing onclick listener for button.
        generateQrBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(dataEdt.getText().toString())) {
                      
                    // if the edittext inputs are empty then execute 
                    // this method showing a toast message.
                    Toast.makeText(MainActivity.this, "Enter some text to generate QR Code", Toast.LENGTH_SHORT).show();
                } else {
                    // below line is for getting 
                    // the windowmanager service.
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                      
                    // initializing a variable for default display.
                    Display display = manager.getDefaultDisplay();
                      
                    // creating a variable for point which 
                    // is to be displayed in QR Code.
                    Point point = new Point();
                    display.getSize(point);
                      
                    // getting width and 
                    // height of a point
                    int width = point.x;
                    int height = point.y;
                      
                    // generating dimension from width and height.
                    int dimen = width < height ? width : height;
                    dimen = dimen * 3 / 4;
                      
                    // setting this dimensions inside our qr code
                    // encoder to generate our qr code.
                    qrgEncoder = new QRGEncoder(dataEdt.getText().toString(), null, QRGContents.Type.TEXT, dimen);
                    try {
                        // getting our qrcode in the form of bitmap.
                        bitmap = qrgEncoder.encodeAsBitmap();
                        // the bitmap is set inside our image 
                        // view using .setimagebitmap method.
                        qrCodeIV.setImageBitmap(bitmap);
                    } catch (WriterException e) {
                        // this method is called for 
                        // exception handling.
                        Log.e("Tag", e.toString());
                    }
                }
            }
        });
    }
}


步骤4:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    
  
    
    

步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.WriterException;
import androidmads.library.qrgenearator.QRGContents;
import androidmads.library.qrgenearator.QRGEncoder;
  
public class MainActivity extends AppCompatActivity {
  
    // variables for imageview, edittext,
    // button, bitmap and qrencoder.
    private ImageView qrCodeIV;
    private EditText dataEdt;
    private Button generateQrBtn;
    Bitmap bitmap;
    QRGEncoder qrgEncoder;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing all variables.
        qrCodeIV = findViewById(R.id.idIVQrcode);
        dataEdt = findViewById(R.id.idEdt);
        generateQrBtn = findViewById(R.id.idBtnGenerateQR);
  
        // initializing onclick listener for button.
        generateQrBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(dataEdt.getText().toString())) {
                      
                    // if the edittext inputs are empty then execute 
                    // this method showing a toast message.
                    Toast.makeText(MainActivity.this, "Enter some text to generate QR Code", Toast.LENGTH_SHORT).show();
                } else {
                    // below line is for getting 
                    // the windowmanager service.
                    WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
                      
                    // initializing a variable for default display.
                    Display display = manager.getDefaultDisplay();
                      
                    // creating a variable for point which 
                    // is to be displayed in QR Code.
                    Point point = new Point();
                    display.getSize(point);
                      
                    // getting width and 
                    // height of a point
                    int width = point.x;
                    int height = point.y;
                      
                    // generating dimension from width and height.
                    int dimen = width < height ? width : height;
                    dimen = dimen * 3 / 4;
                      
                    // setting this dimensions inside our qr code
                    // encoder to generate our qr code.
                    qrgEncoder = new QRGEncoder(dataEdt.getText().toString(), null, QRGContents.Type.TEXT, dimen);
                    try {
                        // getting our qrcode in the form of bitmap.
                        bitmap = qrgEncoder.encodeAsBitmap();
                        // the bitmap is set inside our image 
                        // view using .setimagebitmap method.
                        qrCodeIV.setImageBitmap(bitmap);
                    } catch (WriterException e) {
                        // this method is called for 
                        // exception handling.
                        Log.e("Tag", e.toString());
                    }
                }
            }
        });
    }
}

输出:

检出项目: https : //github.com/ChaitanyaMunje/QRCodeGenerator

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!