banner



Is There An App That Scans Barcodes And Calculates Total

Overview

Scan Kit scans, parses, and generates major 1D and 2D barcodes, helping you quickly build barcode scanning functions into your apps.
Scan Kit automatically detects, magnifies, and recognizes barcodes from a distance, and is also able to scan a very small barcode in the same way. It works even in suboptimal situations, such as in dim light condition or when the barcode is reflective, dirty, blurry, or printed on a cylindrical surface. This leads to a high scanning success rate, and an improved user experience.

What You Will Create

In this codelab, you will create an app that scans barcodes in the Customized View mode.

What You Will Learn

In this codelab, you will learn how to:

  • Integrate the HMS Core SDK.
  • Add permissions required for the barcode scanning function.
  • Call the barcode scanning capabilities of Scan Kit.

If you are using Android Studio, you can integrate the HMS Core SDK via the Maven repository. Before you start developing an app, integrate the HMS Core SDK into your Android Studio project.

Adding the AppGallery Connect Configuration File of Your App

If you have enabled certain services in AppGallery Connect, add the agconnect-services.json file to your app.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find your project and click the app for which you want to integrate the HMS Core SDK.
  3. Go to Project settings > General information. In the App information area, download the agconnect-services.json file.
  4. Copy the agconnect-services.json file to the app-level directory of your Android Studio project.

Configuring the Maven Repository Address for the HMS Core SDK

  1. Open the build.gradle file in the root directory of your Android Studio project.
  2. Add the AppGallery Connect plugin and the Maven repository address.
    • Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
    • Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
    • If the agconnect-services.json file has been added to the app, go to buildscript > dependencies and add the AppGallery Connect plugin configuration.
                        buildscript {      repositories {          google()          jcenter()          // Configure the Maven repository address for the HMS Core SDK.          maven {url 'https://developer.huawei.com/repo/'}      }      dependencies {          ...          // Add the AppGallery Connect plugin configuration. You are advised to use the latest plugin version.          classpath 'com.huawei.agconnect:agcp:1.6.0.300'      }  }    allprojects {      repositories {          google()          jcenter()          // Configure the Maven repository address for the HMS Core SDK.          maven {url 'https://developer.huawei.com/repo/'}      }  }                                  

Adding Build Dependencies

  1. Open the build.gradle file in the app-level directory.
  2. Add build dependencies in the dependencies block, and replace {version} with the actual SDK version number, for example, implementation 'com.huawei.hms:scan:1.3.2.300'. For details about the version number, please refer to the Version Change History.
                  dependencies {      implementation 'com.huawei.hms:scan:{version}'  }                          
  3. Add the AppGallery Connect plugin configuration in either of the following methods:
    • Method 1: Add the following information under the declaration in the file header:
                        apply plugin: 'com.huawei.agconnect'                                  
    • Method 2: Add the plugin configuration in the plugins block.
                        plugins {      id 'com.android.application'      // Add the following configuration:      id 'com.huawei.agconnect'  }                                  
  4. Synchronize the project. After completing the preceding configuration, click the synchronization icon on the toolbar to synchronize the Gradle files.
  1. Before integrating Scan Kit, declare the required permissions in the AndroidManifest.xml file, which are CAMERA (camera permission) and READ_EXTERNAL_STORAGE (file read permission). If you use the sample code, skip this step because the permissions have already been declared.
                  <!--Camera permission-->  <uses-permission android:name="android.permission.CAMERA" />  <!--File read permission-->  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />  <uses-feature android:name="android.hardware.camera" />  <uses-feature android:name="android.hardware.camera.autofocus" />                          
  2. Dynamically request the permissions in the MainActivity.java file.
    Java sample code:
                  public static final int DEFINED_CODE = 222;  public static final int REQUEST_CODE_SCAN = 111;  public void newViewBtnClick(View view) {      // Replace DEFINED_CODE with the code that you customize for receiving the permission verification result.       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {       this.requestPermissions(               new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},               DEFINED_CODE);   }   }   @Override   public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {       if (permissions == null || grantResults == null || grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {           return;       }         if (requestCode == DEFINED_CODE) {           // Go to the customized scanning UI DefinedActivity.           this.startActivityForResult(new Intent(this, DefinedActivity.class), REQUEST_CODE_SCAN);       }   }                          

    Kotlin sample code:

                  val DEFINED_CODE = 222  val REQUEST_CODE_SCAN = 111  fun newViewBtnClick(view:View?) {      // Replace DEFINED_CODE with the code that you customize for receiving the permission verification result.      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {      this.requestPermissions(              arrayOf(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE),              DEFINED_CODE)  }  }  override fun onRequestPermissionsResult(requestCode:Int, permissions:Array<out String>, grantResults:IntArray) {      if (permissions == null || grantResults.size < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {          return      }        if (requestCode == DEFINED_CODE) {          // Go to the customized scanning UI DefinedActivity.          this.startActivityForResult(Intent(this, DefinedActivity::class.java), REQUEST_CODE_SCAN)      }  }                          

Scan Kit can be called in four modes. Their differences are described in the Development Guide. In this codelab, this kit is called in Customized View mode.

Customizing the Elements on the Scanning UI

Customize elements on the scanning UI as required, such as the barcode scanning box and prompt. For details, please refer to Custom Elements for the Scanning UI in Customized View Mode.

Implementing Camera Scanning

To scan barcodes using the camera in the customized activity, add the following to the DefinedActivity.java file:
Java sample code:

          // Import all dependencies suggested by Android Studio.  int SCAN_FRAME_SIZE=200;  private RemoteView remoteView;  public static final String SCAN_RESULT = "scanResult";      @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);                   setContentView(R.layout.activity_defined);             // 1. Obtain the screen resolution to calculate the size of the scanning box.          DisplayMetrics dm = getResources().getDisplayMetrics();          float density = dm.density;          // 2. Obtain the screen size.          int mScreenWidth = getResources().getDisplayMetrics().widthPixels;          int mScreenHeight = getResources().getDisplayMetrics().heightPixels;             int scanFrameSize = (int) (SCAN_FRAME_SIZE * density);             // 3. Calculate the position of the scanning box. Currently, it is in the middle of the screen.          // (Optional) Set the position of the scanning box. If no position is set, the scanning box will be in the middle of the screen by default.          Rect rect = new Rect();          rect.left = mScreenWidth / 2 - scanFrameSize / 2;          rect.right = mScreenWidth / 2 + scanFrameSize / 2;          rect.top = mScreenHeight / 2 - scanFrameSize / 2;          rect.bottom = mScreenHeight / 2 + scanFrameSize / 2;                // Initialize RemoteView and set a callback to receive the scanning result.          remoteView = new RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.ALL_SCAN_TYPE).build();  remoteView.setOnResultCallback(new OnResultCallback() {              @Override              public void onResult(HmsScan[] result) {                    if (result != null && result.length > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {              Intent intent = new Intent();              intent.putExtra(SCAN_RESULT, result[0]);              setResult(RESULT_OK, intent);              DefinedActivity.this.finish();   }   }                  });             // Add the defined RemoteView to the screen layout.          FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);          FrameLayout frameLayout = findViewById(R.id.rim);          frameLayout.addView(remoteView, params);     }                  

Kotlin sample code:

          // Import all dependencies suggested by Android Studio.  private var remoteView:RemoteView?=null  val SCAN_RESULT = "scanResult"      override fun onCreate(savedInstanceState:Bundle?) {          super.onCreate(savedInstanceState)                   setContentView(R.layout.activity_defined)             // 1. Obtain the screen resolution to calculate the size of the scanning box.          val dm = resources.displayMetrics          val density = dm.density          // 2. Obtain the screen size.          var mScreenWidth = resources.displayMetrics.widthPixels          var mScreenHeight = resources.displayMetrics.heightPixels             var scanFrameSize = (SCAN_FRAME_SIZE * density)             // 3. Calculate the position of the scanning box. Currently, it is in the middle of the screen.          // (Optional) Set the position of the scanning box. If no position is set, the scanning box will be in the middle of the screen by default.          val rect = Rect()          rect.left = (mScreenWidth / 2 - scanFrameSize / 2).toInt()          rect.right = (mScreenWidth / 2 + scanFrameSize / 2).toInt()          rect.top = (mScreenHeight / 2 - scanFrameSize / 2).toInt()          rect.bottom = (mScreenHeight / 2 + scanFrameSize / 2).toInt()                // Initialize RemoteView and set a callback to receive the scanning result.          remoteView =  RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.ALL_SCAN_TYPE).build()  remoteView?.setOnResultCallback{result->                     if (result != null && result.size > 0 && result[0] != null && !TextUtils.isEmpty(result[0]!!.getOriginalValue())) {              val intent = Intent()              intent.putExtra(SCAN_RESULT, result[0])              setResult(RESULT_OK, intent)              this@DefinedActivity.finish()   }            }             // Add the defined RemoteView to the screen layout.          val params =  FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)          val frameLayout = findViewById(R.id.rim1)          frameLayout.addView(remoteView, params)     }                  

To add RemoteView lifecycle management, add the following to the DefinedActivity.java file:
Java sample code:

          @Override  protected void onStart() {      super.onStart();      remoteView.onStart();  }    @Override  protected void onResume() {      super.onResume();      remoteView.onResume();  }    @Override  protected void onPause() {      super.onPause();      remoteView.onPause();  }    @Override  protected void onDestroy() {      super.onDestroy();      remoteView.onDestroy();  }    @Override  protected void onStop() {      super.onStop();      remoteView.onStop();  }                  

Kotlin sample code:

          override  protected fun onStart() {      super.onStart()      remoteView?.onStart()  }    override  protected fun onResume() {      super.onResume()      remoteView?.onResume()  }    override  protected fun onPause() {      super.onPause()      remoteView?.onPause()  }    override  protected fun onDestroy() {      super.onDestroy()      remoteView?.onDestroy()  }    override  protected fun onStop() {      super.onStop()      remoteView?.onStop()  }                  

Processing the Scanning Result

Add the following code to the MainActivity.java file for processing the scanning result:
Java sample code:

          @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {       // Obtain the result.       super.onActivityResult(requestCode, resultCode, data);       if (resul***RESULT_OK*** ESULT_OK || data == null) {           return;       }       if (requestCode == REQUEST_CODE_SCAN) {           HmsScan hmsScan = data.getParcelableExtra(DefinedActivity.SCAN_RESULT);           if (hmsScan != null && !TextUtils.isEmpty(hmsScan.getOriginalValue())) {               Toast.makeText(MainActivity.this, hmsScan.getOriginalValue(),***LENGTH_SHORT***GTH_SHORT).show();           }       }   }                  

Kotlin sample code:

          override  protected fun onActivityResult(requestCode:Int, resultCode:Int, data:Intent?) {       // Obtain the result.       super.onActivityResult(requestCode, resultCode, data)       if (resul***RESULT_OK*** ESULT_OK || data == null) {           return       }       if (requestCode == REQUEST_CODE_SCAN) {           var hmsScan = data?.getParcelableExtra<HmsScan>(DefinedActivity.SCAN_RESULT)           if (hmsScan != null && !TextUtils.isEmpty(hmsScan?.getOriginalValue())) {               Toast.makeText(this@MainActivity, hmsScan?.getOriginalValue(),***LENGTH_SHORT***GTH_SHORT).show()           }       }   }                  

Well done. You have successfully completed this codelab and learned how to:

  • Integrate Scan Kit.
  • Use the Customized View mode of Scan Kit to scan barcodes.
For more information about Scan Kit, please visit our official website. If you encounter any problems during the development, please refer to FAQs.

Is There An App That Scans Barcodes And Calculates Total

Source: https://developer.huawei.com/consumer/en/codelab/ScanKit/index.html

Posted by: thompsonduccies1960.blogspot.com

0 Response to "Is There An App That Scans Barcodes And Calculates Total"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel