teaching machines

CS491: Homework02 xiongchu

October 19, 2011 by . Filed under cs491 mobile, fall 2011, postmortems.

I implemented an application that scans Universal Product Codes (UPC). The user is then allowed to insert information about the product and store the UPC, brand name, product name, and a small description of the product into a SQLite database.

I used ZXing’s (Zebra Crossing) Barcode Scanner application to do the UPC scanning. My application requires that you have this application installed, if not my application was start Android Market and allow the user to install the required application.

Scanning Via Intent

public Button.OnClickListener mScan = new Button.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.setPackage("com.google.zxing.client.android");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
};

The above code shows how to start the scanning activity. First create an intent passing the action, in the above case it is the package name follow by the action (SCAN). The setPackage() call is optional, it is for explicitly specifying the package name. The following line, putExtra() call, specifies what we want to scan. The above code specifies “QR_CODE_MODE”, which scans only quick response code (QR). In my application I used “PRODUCT_MODE”, indicating I want to scan products. There are other modes as well, you can find them here. You must start the activity for a result.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            // Handle successful scan
        } else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
        }
    }
}

Next you must implement the onActivityResult() of your Activity. To retrieve the scan results, you call intent.getStringExtra(“SCAN_RESULT”). In my case this will return the UPC. Thats all to it. But scanning via intent requires you to have the barcode scanner application installed. It is also possible to build the scanner source code with your application, but I did not look into this.

Another way is to prompt the user to allow downloading the ZXing Team Barcode Scanner application from Android Market. The code below describes this method. The “com.google.zxing.client.android” specifies the package name you want. Then you create the intent and start the activity.

Uri uri = Uri.parse("market://search?q=" +
    "pname:com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri); // Create the intent
            
try {
     MainActivity.this.startActivity(intent); // Start the Activity
} catch (ActivityNotFoundException e) {
  // Unable to start Android Market
}