Android barcode application

Source: Internet
Author: User
Tags xml attribute

Android support library for barcode scanning and Recognition

Android supports barcode scanning. However, if you do not have a real machine, you cannot understand whether this function is an application or an API call function. However, you can find a free and open-source Android code processing library on the Internet. See:

Http://code.google.com/p/zxing

It can be installed on Android as an application. For details, see:

Http://code.google.com/p/zxing/wiki/GettingStarted

Alternatively, use this function in another program:

Http://code.google.com/p/zxing/wiki/ScanningViaIntent

 

Compile the simplest Android barcode scanning function

There is already a third-party open-source bar code identification Library (zxing) in Java. In fact, you only need to call the implementation of this third-party library to scan the bar code in your own applications. The android support library for scanning and bar code recognition does not have the G1 mobile phone. You can try it now.

To be able to call zxing, you must first install barcode labels in Google market:

 

To be able to call zxing, you must first install barcode labels in Google market:

The program is very simple. The first interface is:

The second interface jumps to the activity provided by the zxing library for barcode scanning. The scan here generates the URL of this site in the QR code.

The QR code can be recognized in an instant, and then returned to the program from the zxing activity, showing the entry content:

Writing code is simple.

Java code:

Package com. easymorse;

Import Android. App. activity;
Import Android. content. intent;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Import Android. widget. textview;

Public class showbarcodeactivity extends activity implements onclicklistener {

Private button;

Private textview;

/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

This. Button = (button) This. findviewbyid (R. Id. button01 );
This. Button. setonclicklistener (this );

This. textview = (textview) This. findviewbyid (R. Id. Hello );
}

@ Override
Public void onclick (view ){
Intent intent = new intent ("com. Google. zxing. Client. Android. Scan ");
Intent. putextra ("scan_mode", "qr_code_mode ");
This. startactivityforresult (intent, 0 );
}

@ Override
Protected void onactivityresult (INT requestcode, int resultcode, intent data ){
If (requestcode! = 0 ){
Return;
}

This. textview. settext (data. getstringextra ("scan_result "));
}
}

Main. XML in the layout directory:

<? XML version = "1.0" encoding = "UTF-8"?>
<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android%22
Android: Orientation = "vertical"
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
>
<Textview
Android: Id = "@ + ID/hello"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "@ string/hello"
/>

<Button Android: text = "@ string/button01" Android: Id = "@ + ID/button01" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> </button>
</Linearlayout>

Strings. XML in the values directory

<? XML version = "1.0" encoding = "UTF-8"?>
<Resources>
<String name = "hello"> no scan results are currently displayed. </String>
<String name = "app_name"> shopping tips </string>
<String name = "button01"> click to start scanning... </String>
</Resources>

In this example, we can also see that android is powerful and can reuse the services or activities of other applications.

 

Android scans product barcode

The simplest Android barcode scanning function just now can only scan QR codes. If you want to scan a regular product barcode, You need to seat it in the program and modify it a little bit.

Interface changes:

Effect of bar code scanning:

Display scan results (the recognition speed is significantly lower than the QR code ):

Code changes:

Package com. easymorse;

Import Android. App. activity;
Import Android. content. intent;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. View. View. onclicklistener;
Import Android. widget. Button;
Import Android. widget. textview;

Public class showbarcodeactivity extends activity {

Private button;

Private button button2;

Private textview;

/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

This. Button = (button) This. findviewbyid (R. Id. button01 );
This. Button. setonclicklistener (New onclicklistener (){

@ Override
Public void onclick (view v ){
Intent intent = new intent (
"Com. Google. zxing. Client. Android. Scan ");
Intent. putextra ("scan_mode", "qr_code_mode ");
Startactivityforresult (intent, 0 );
}
});

This. button2 = (button) This. findviewbyid (R. Id. button02 );
This. button2.setonclicklistener (New onclicklistener (){

@ Override
Public void onclick (view v ){
Intent intent = new intent (
"Com. Google. zxing. Client. Android. Scan ");
Intent. putextra ("scan_mode", "ean_13 ″);
Startactivityforresult (intent, 0 );
}
});

This. textview = (textview) This. findviewbyid (R. Id. Hello );
}

@ Override
Protected void onactivityresult (INT requestcode, int resultcode, intent data ){
If (requestcode! = 0 ){
Return;
}

This. textview. settext (data. getstringextra ("scan_result "));
}
}

After writing this example, you can see that you do not need to write it now:

Intent. putextra ("scan_mode", "qr_code_mode ");

Zxing's current library can automatically identify which encoding is used. If it is written, it specifies the type rather than the encoding of other types. In fact, the above:

Intent. putextra ("scan_mode", "ean_13 ″);

Incorrect. For specific constant parameters, see:

Http://zxing.org/w/docs/javadoc/constant-values.html

The above content is not modified. The correct source code is shared in the Svn of Google Code. See:

Http://easymorse.googlecode.com/svn/tags/barcode.proto.0.1.0/

 

 

An example of recognizing the ISBN number of a book and outputting the query results

I wrote a technical prototype, used a mobile phone to identify the ISBN barcode of a book, and then output the information of the book corresponding to the ISBN through the API of douban.com.

The example is simple. Click a button to enter the zxing activity, which is used to scan the ISBN number of the book.

Some problems still occurred this time when zxing's scanning function was used. My Nexus One Camera is dirty, making it unrecognizable after focus, or very slow to recognize. I was shocked because there was no problem before.

After changing several versions of zxing, the problem persists. After the camera is wiped, the problem is immediately solved.

The pixel and Autofocus capabilities of Nexus One may also include CPU processing factors, slightly align the bar code, and get immediate results. The previous G1.

This also makes it difficult to capture the above, because the scanning will end in an instant. What should we do? I rubbed my hands on the camera a few times.

After finding a book, I can get the XML of the book through the Douban API. Here I want to say that Douban's book information is still comprehensive, and I also found the information using foreign books.

Because the China Unicom WCDMA card is used, the whole process is very fast.

The following describes some key points in the code.

How to scan a barcode

Now we do bar code scanning. Java generally uses zxing. Zxing has multiple reuse methods. The simplest method is to install zxing software through Google market. In your own applications, you can call the zxing scan barcode activity through intent, and then return the scan results to your own activity.

A complicated method is to include the zxing library in your own program, which is suitable for formal applications.

This document uses the former.

Sample Code

For the sample source code, see:

Http://easymorse.googlecode.com/svn/tags/sou.book-0.2

A simpler example can be used to understand the basic process of calling zxing and Douban APIs. For details, see:

Http://easymorse.googlecode.com/svn/tags/sou.book-0.1

Implement activity jump

In version 0.2, three activities are involved. First, the activity for searching books is shown in the top figure. Click the button to enter the zxing activity. Visually, after zxing obtains the ISBN number, it enters the third activity, showing the detailed information of the book.

In fact, after zxing obtains the ISBN, it returns the activity for searching books, but the activity immediately initiates a new intent to enter the new activity. In addition, the parameters between activities are shared by intent.

Run the following code to create a new activity and set parameters:

Intent intent = new intent ();
Intent. setclass (this, searchbookactivity. Class );
Intent. putextra ("ISBN", Data. getextras (). getstring ("scan_result "));
This. startactivity (intent );

The following parameters are obtained from intent:

This. getintent (). getextras (). getstring ("ISBN"); for how to use zxing, refer to my other example. Android scans the product barcode. Webview local page usage considerations

Use webview in the activity that displays the query result of a book, so that the display can be more flexible and simple.

There are multiple ways to display a page, such as a page on a remote server, which requires support from the server. It seems quite easy, especially when there are iPhone, Android, and other heterogeneous terminals. Mobile phone developers can leave this part empty and hand it over to the server for resolution. It is also a unified solution.

However, in practice, there are two problems:

Server developers must implement different styles for different mobile clients, and server developers are often not equipped with mobile phone devices, which is indeed hard to achieve, is it necessary to assign iPhone, Android, and s60 mobile phones to a server-side developer who is adapted? Mobile Terminal developers cannot flexibly control the details in webview. webview (Android environment, similar to iPhone environment) supports accessing services or objects of mobile phones through JavaScript, but this is platform-related, android has its own code, and iPhone also has its own code, which is difficult to solve on the server.

In this prototype, I tried to solve the problem, that is, when the HTML page is at the mobile terminal's local location, the mobile phone end interacts with the server, only the data is obtained, without the display style (that is, the content of the HTML page), the mobile phone uses JavaScript to inject the obtained data into the local page for display.

The advantages of this method are:

Interaction between the mobile phone end and the server end is to obtain data, which is common to various mobile phone systems. This method is similar to Ajax, and the requirements for data traffic will also decrease; mobile phone developers can flexibly determine the page style and Interactive Actions.

In this example, place HTML and CSS in the Assets Directory of the project. In addition, there is an image under the Directory, which is used to hold the image when it is not loaded to the library image. Imagine that if webview is not used, this requirement requires programming and processing, which is complicated. For details, see the processing in Android asynchronous loading of listview images.

The code for webview implementation is simple. This is a simpler example. For details, see webview for Android. Code in this example:

This. resultweb = (webview) This. findviewbyid (R. Id. resultweb );

This. resultweb. getsettings (). setsuppzoom zoom (false );

This. resultweb. getsettings (). setjavascriptcanopenwindowsautomatically (

True );

This. resultweb. getsettings (). setjavascriptenabled (true );

This. resultweb. loadurl (http: // file /// android_asset/results.html );

 

Note that setjavascriptenabled enables JavaScript, otherwise Javascript is invalid.

Javascript interoperability between Android Java and HTML pages

Communication between JavaScript and Java. In this example, it is relatively simple to call Java only through JavaScript. To call Javascript in Java, you must start a separate thread.

You need to create a javascript called interface object for the webview object:

This. resultweb. addjavascriptinterface (new object (){

Public String getbookname (){

Return bookinfo. getname ();

}

Public String getbooksummary (){

Return bookinfo. getsummary ();

}

Public String getbookimageurl (){

Return bookinfo. getimageurl ();

}

Public String getbookauthor (){

Return bookinfo. getauthor ();

}

}, "Searchresult ");

 

The first parameter is the object called by JavaScript, and the second parameter is the name of the called object.

Let's see how to call this object in javascript:

Document. getelementbyid ("bookname"). innerhtml = Window. searchresult. getbookname ();

The window object has multiple searchresult object attributes. The searchresult is the second parameter in the above method. With this name, the internal class object created by the first parameter is called.

Using Douban API

Official Douban API Website:

Http://www.douban.com/service/apidoc/

Here, we only use the XML function for getting Library Information Based on ISBN. Here:

Http://www.douban.com/service/apidoc/reference/subject

If you use this API anonymously, you have certain restrictions:

API calls are limited to 10 requests per minute.

The number of calls here is per IP address. For mobile apps, it should be enough to scan books more than 6 seconds.

Parse the query results of Douban XML

The xmlpull API of Android is used to parse the XML query result of Douban.

The difference between XML parsing through xmlpull and Android is that the latter obtains the XML Attribute Value and obtains the text content in the node.

Required:

If (I = xmlpullparser. start_tag

& Parser. getname (). Equals ("attribute ")

& Parser. getattributevalue (0). Equals ("title ")){

Bookinfo. setname (parser. nexttext ());

Log. V ("soubook", "title>" + bookinfo. getname ());

Continue;

}

 

You can use the parser. nexttext () method. In addition, pay attention to the completion of this loop after the acquisition is complete.

HTML and CSS

In this example, the webview that displays the query results uses an ugly gray background, mainly to demonstrate that external CSS can be used with HTML.

Similarly, you can reference external JavaScript on the HTML page and intend to add jquery to the next version.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.