QR Code Scanner con Android studio

QR  Code (Quick Response Code) è un codice a barre bidimensionale che viene letto tramite la fotocamera di un dispositivo .
In questo esempio andremo a creare un QR Code Scanner utilizzando la libreria ZXing,
e con il metodo IntentIntegrator.parseActivityResult andiamo ad identificare il contenuto del codice QR:

activity_main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity=”center”
android:orientation=”vertical”>

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/button”/>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/text”/>
</LinearLayout>

MainActivity.java
package com.example.qrCode.activities;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.qrCode.R;
import android.widget.*;
import android.view.*;
import com.google.zxing.integration.android.*;
import android.content.*;

public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


textView=findViewById(R.id.text);
button=findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener(){


@Override
public void onClick(View v){

IntentIntegrator integrator =new
IntentIntegrator(MainActivity.this);
integrator.setDesiredBarcodeFormats(
integrator.ALL_CODE_TYPES);
integrator.setOrientationLocked(true);
integrator.setBeepEnabled(false);
integrator.setPrompt(“Scan”);
integrator.initiateScan();


}

});


    }

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{

IntentResult result=IntentIntegrator.parseActivityResult(
requestCode,resultCode,data);
if (result != null){
if(result.getContents()==null){
Toast.makeText(this,”Scan cancelled”,
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,”Scanned”+result.
getContents(),Toast.LENGTH_LONG).show();

textView.setText(result.getContents());


}

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

}
}

build.grandler
implementation ‘com.google.zxing:core:3.2.1’
implementation ‘com.journeyapps:zxing-android-embedded:4.1.0’

AndroidManifest.xml
<uses-permission android:name=”android.permission.CAMERA” />
<uses-feature android:name=”android.hardware.camera” />