Blog purpose for android basic example for android app developer. any query please my contact

Saturday, 19 June 2021

android studio barcode scanner example

 android studio barcode scanner example


This Article Today Learn android studio barcode scanner example follows the full Source code android studio barcode scanner example.


1.build.gradle:

compile 'com.journeyapps:zxing-android-embedded:2.0.1@aar'

    compile 'com.journeyapps:zxing-android-legacy:2.0.1@aar'

    compile 'com.journeyapps:zxing-android-integration:2.0.1@aar'

    compile 'com.google.zxing:core:3.0.1'



2.MainActivity.java:


package com.barcode.scanner.free.app;


import android.Manifest;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.PackageManager;

import android.os.Build;

import android.os.Bundle;

import android.os.StrictMode;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.TextView;

import android.widget.Toast;


import androidx.annotation.NonNull;

import androidx.annotation.RequiresApi;

import androidx.core.app.ActivityCompat;

import androidx.core.content.ContextCompat;

import com.google.zxing.integration.android.IntentIntegrator;

import com.google.zxing.integration.android.IntentResult;



public class MainActivity extends Activity {

    private String codeFormat,codeContent;

    private TextView formatTxt, contentTxt;

 

    public static final int REQUEST_PERMISSIONS = 1;

    boolean boolean_permission;

    private static final int MY_CAMERA_REQUEST_CODE = 100;


    @RequiresApi(api = Build.VERSION_CODES.M)

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        formatTxt = (TextView)findViewById(R.id.scan_format);

        contentTxt = (TextView)findViewById(R.id.scan_content);


      


       // fn_permission();


        requestStoragePermission();

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

 //       getMenuInflater().inflate(R.menu.menu_home, menu);

        return true;

    }


    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();


        //noinspection SimplifiableIfStatement


        return super.onOptionsItemSelected(item);

    }


    /**

     * event handler for scan button

     * @param view view of the activity

     */

    public void scanNow(View view){

        IntentIntegrator integrator = new IntentIntegrator(this);

        integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);

        integrator.setPrompt(this.getString(R.string.scan_bar_code));

        integrator.setResultDisplayDuration(0);

        integrator.setWide();  // Wide scanning rectangle, may work better for 1D barcodes

        integrator.setCameraId(0);  // Use a specific camera of the device

        integrator.initiateScan();

        AdRequest adRequest = new AdRequest.Builder().build();

        mAdView.loadAd(adRequest);


    }



    /**

     * function handle scan result

     * @param requestCode scanned code

     * @param resultCode  result of scanned code

     * @param intent intent

     */

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        //retrieve scan result

        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);


        if (scanningResult != null) {

            //we have a result

            codeContent = scanningResult.getContents();

            codeFormat = scanningResult.getFormatName();


            // display it on screen

            formatTxt.setText("FORMAT: " + codeFormat);

            contentTxt.setText("CONTENT: " + codeContent);


        }else{

            Toast toast = Toast.makeText(getApplicationContext(),"No scan data received!", Toast.LENGTH_SHORT);

            toast.show();

        }

    }

   /* public void onCreate() {

        super.onCreate();

        //Allowing Strict mode policy for Nougat support

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();

        StrictMode.setVmPolicy(builder.build());

    }

    */

    public void onCreate(){

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();

        StrictMode.setVmPolicy(builder.build());



    }

    @RequiresApi(api = Build.VERSION_CODES.M)

   /* private void fn_permission() {

        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) ||

                (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {


            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))) {

            } else {

                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},

                        REQUEST_PERMISSIONS);


            }


            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {

            } else {

                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},

                        REQUEST_PERMISSIONS);


            }

        } else {

            boolean_permission = true;



        }


        if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);

        }



        }

*/



  /*  @Override

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_PERMISSIONS) {


            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                boolean_permission = true;



            } else {

                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();


            }


            if (requestCode == MY_CAMERA_REQUEST_CODE) {

                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();

                }

            }

        }

    }*/




    private void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,

                Manifest.permission.CAMERA)) {

            new AlertDialog.Builder(this)

                    .setTitle("Permission needed")

                    .setMessage("This permission is needed because of this and that")

                    .setPositiveButton("ok", new DialogInterface.OnClickListener() {

                        @Override

                        public void onClick(DialogInterface dialog, int which) {

                            ActivityCompat.requestPermissions(MainActivity.this,

                                    new String[] {Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);



                        }

                    })

                    .setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                        @Override

                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();

                        }

                    })

                    .create().show();

        } else {

            ActivityCompat.requestPermissions(this,

                    new String[] {Manifest.permission.CAMERA}, MY_CAMERA_REQUEST_CODE);



        }

    }

    @Override

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == MY_CAMERA_REQUEST_CODE)  {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();

            } else {

                Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();

            }

        }

    }



}



3.activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:background="@color/cardview_shadow_start_color"

    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">


    <TextView

        android:id="@+id/tv_welcome"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_marginBottom="@dimen/activity_vertical_margin"

        android:text="Barcode Scanner" />


    <TextView

        android:layout_below="@+id/tv_welcome"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/tv_blog_url"

        android:layout_marginBottom="@dimen/activity_vertical_margin"

        android:visibility="gone"/>


    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/tv_blog_url"

        android:text="@string/btn_scan_now"

        android:layout_centerHorizontal="true"

        android:onClick="scanNow"

        android:layout_marginBottom="@dimen/activity_vertical_margin"

        android:id="@+id/btn_scan_now" />


    <TextView

        android:id="@+id/scan_format"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:textIsSelectable="true"

        android:layout_below="@+id/btn_scan_now"

        android:gravity="center_horizontal"

        android:layout_marginBottom="@dimen/activity_vertical_margin" />

    <TextView

        android:id="@+id/scan_content"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:textIsSelectable="true"

        android:layout_below="@+id/scan_format"

        android:layout_marginBottom="@dimen/activity_vertical_margin"

        android:gravity="center_horizontal" />

</RelativeLayout>




4.AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.barcode.scanner.free.app">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.CAMERA" />

    <uses-feature android:name="android.hardware.Camera" android:required="true" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application

        android:allowBackup="true"

        android:icon="@drawable/barcode"

        android:label="@string/app_name"

        android:roundIcon="@drawable/barcode"

        android:supportsRtl="true"

        android:theme="@style/Theme.BarcodeScannerApp">


        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <provider

            android:name="androidx.core.content.FileProvider"

            android:authorities="com.barcode.scanner.free.app.provider"

            android:exported="false"

            android:grantUriPermissions="true">

            <meta-data

                android:name="android.support.FILE_PROVIDER_PATHS"

                android:resource="@xml/provider_paths" />

        </provider>

    </application>

    <meta-data

        android:name="com.google.android.gms.vision.DEPENDENCIES"

        android:value="barcode" />

</manifest>


5.strings.xml:


<resources>

    <string name="app_name">Barcode Scanner app</string>

    <string name="hello_world">Welcome to Android bar Code Scanner By RajDeol. For more details visit my blog </string>

    <string name="blog_url">http://blog.whomeninja.in/android-barcode-scanner/</string>

    <string name="action_settings">Settings</string>

    <string name="btn_scan_now">Scan Now</string>

    <string name="scan_bar_code">Scan a Bar Code</string>


</resources>


6.dimens.xml:


<resources>

    <!-- Default screen margins, per the Android Design guidelines. -->

    <dimen name="activity_horizontal_margin">16dp</dimen>

    <dimen name="activity_vertical_margin">16dp</dimen>


    <dimen name="standard_padding">8dip</dimen>

    <dimen name="half_padding">4dip</dimen>


</resources>




No comments:

Post a Comment