使用Zxing及豆瓣API

 本文原创,转载请注明原文地址:http://maosidiaoxian.iteye.com/blog/1743296或我在sinaapp上的博客:http://msdxblog.sinaapp.com/?p=716。

最近在做团队图书管理的一个Android端。因为需要通过手机扫描来输入图书信息(人工一条一条地输入,作为技术人员太受不了了),需要使用ZXing的API扫描图书ISBN,及使用豆瓣API来获取图书信息。

由于时间关系,这里没有使用ZXing的jar包,而是下载并安装了它的开源项目——条码扫描器,然后调用里面的Activity扫描再获取结果。
首先到市场下载Barcode Scaner(或搜索条码扫描器),下载安装。
下面先贴上Activity的布局代码,因为是demo版,而且在内部使用,就没去好好做布局设计,只是把需要的控件都写上。

Xml代码 复制代码 收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6.  
  7. <Button
  8. android:id="@+id/home_scan"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="@string/button_scan" />
  12.  
  13. <TextView
  14. android:id="@+id/home_result_scan"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content" />
  17.  
  18. <TextView
  19. android:id="@+id/home_book_info"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content" />
  22.  
  23. <Button
  24. android:id="@+id/home_upload_result"
  25. android:layout_width="wrap_content"
  26. android:layout_height="wrap_content"
  27. android:text="@string/button_upload" />
  28.  
  29. <TextView
  30. android:id="@+id/home_result_upload"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:singleLine="false" />
  34.  
  35. <LinearLayout
  36. android:layout_width="fill_parent"
  37. android:layout_height="wrap_content" >
  38.  
  39. <Button
  40. android:id="@+id/home_borrow_book"
  41. android:layout_width="wrap_content"
  42. android:layout_height="wrap_content"
  43. android:text="@string/borrow_book" />
  44.  
  45. <Spinner
  46. android:id="@+id/home_users"
  47. android:layout_width="wrap_content"
  48. android:layout_height="wrap_content"
  49. android:layout_gravity="right" />
  50. </LinearLayout>
  51.  
  52. <Button
  53. android:id="@+id/home_return_book"
  54. android:layout_width="wrap_content"
  55. android:layout_height="wrap_content"
  56. android:text="@string/return_book" />
  57.  
  58. <Button
  59. android:id="@+id/home_user_manager"
  60. android:layout_width="wrap_content"
  61. android:text="@string/manager_user"
  62. android:layout_height="wrap_content" />
  63.  
  64. </LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/home_scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_scan" />

    <TextView
        android:id="@+id/home_result_scan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/home_book_info"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/home_upload_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_upload" />

    <TextView
        android:id="@+id/home_result_upload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="false" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/home_borrow_book"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/borrow_book" />

        <Spinner
            android:id="@+id/home_users"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right" />
    </LinearLayout>

    <Button
        android:id="@+id/home_return_book"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/return_book" />

    <Button
        android:id="@+id/home_user_manager"
        android:layout_width="wrap_content"
        android:text="@string/manager_user"
        android:layout_height="wrap_content" />

</LinearLayout>



然后在我们的项目中,写一个Activity来调用Zxing的扫描功能,并通过它返回的结果访问互联网获取信息。

下面是该Activity的代码。这里对于控件及事件的绑定,我使用了自己封装的一个工具(Androidkit)来简化这些代码,所以你们会看到许多类似@AndroidView的注解,这个工具可以在http://code.google.com/p/cfuture-androidkit/获取,或从https://github.com/msdx/androidkit上获得最新代码。

Java代码 复制代码 收藏代码
  1. /*
  2. * @(#)HomeActivity.java Project:bookscan
  3. * Date:2012-12-3
  4. *
  5. * Copyright (c) 2011 CFuture09, Institute of Software,
  6. * Guangdong Ocean University, Zhanjiang, GuangDong, China.
  7. * All rights reserved.
  8. *
  9. * Licensed under the Apache License, Version 2.0 (the "License");
  10. * you may not use this file except in compliance with the License.
  11. * You may obtain a copy of the License at
  12. *
  13. * http://www.apache.org/licenses/LICENSE-2.0
  14. *
  15. * Unless required by applicable law or agreed to in writing, software
  16. * distributed under the License is distributed on an "AS IS" BASIS,
  17. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. * See the License for the specific language governing permissions and
  19. * limitations under the License.
  20. */
  21. package com.sinaapp.msdxblog.bookscan.activity;
  22.  
  23. import org.apache.http.HttpResponse;
  24. import org.apache.http.client.methods.HttpGet;
  25. import org.apache.http.impl.client.DefaultHttpClient;
  26.  
  27. import android.app.Activity;
  28. import android.content.Intent;
  29. import android.database.Cursor;
  30. import android.os.Bundle;
  31. import android.os.Handler;
  32. import android.view.View;
  33. import android.widget.SimpleCursorAdapter;
  34. import android.widget.Spinner;
  35. import android.widget.TextView;
  36.  
  37. import com.sinaapp.msdxblog.androidkit.thread.HandlerFactory;
  38. import com.sinaapp.msdxblog.androidkit.ui.ResBindUtil;
  39. import com.sinaapp.msdxblog.androidkit.ui.UIBindUtil;
  40. import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidRes;
  41. import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidRes.ResType;
  42. import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidView;
  43. import com.sinaapp.msdxblog.androidkit.ui.annotation.OnClick;
  44. import com.sinaapp.msdxblog.bookscan.R;
  45. import com.sinaapp.msdxblog.bookscan.bean.Book;
  46. import com.sinaapp.msdxblog.bookscan.util.DB;
  47. import com.sinaapp.msdxblog.bookscan.util.XMLSax;
  48.  
  49. /**
  50. * @author Geek_Soledad ([email protected])
  51. */
  52. public class HomeActivity extends Activity {
  53. private static final int HOME_ACTIVITY = 1990;
  54. private static final String DOUBAN_API = "http://api.douban.com/book/subject/isbn/";
  55.  
  56. @AndroidView(id = R.id.home_result_scan)
  57. private TextView mTextScan;
  58. @AndroidView(id = R.id.home_book_info)
  59. private TextView mTextBook;
  60. @AndroidView(id = R.id.home_result_upload)
  61. private TextView mTextUpload;
  62. @AndroidView(id = R.id.home_users)
  63. private Spinner mSpinnerUser;
  64.  
  65. @AndroidRes(id = R.string.result_scan, type = ResType.STRING)
  66. private String mStringScan;
  67. @AndroidRes(id = R.string.result_getting, type = ResType.STRING)
  68. private String mStringGetting;
  69. @AndroidRes(id = R.string.book_info, type = ResType.STRING)
  70. private String mStringBookInfo;
  71.  
  72. private Handler mGettingBook;
  73. private Book book;
  74. private DB mDb;
  75. private SimpleCursorAdapter mAdapter;
  76.  
  77. @Override
  78. protected void onCreate(Bundle savedInstanceState) {
  79. super.onCreate(savedInstanceState);
  80. UIBindUtil.bind(this, R.layout.activity_home);
  81. ResBindUtil.bindAllRes(this);
  82. init();
  83. }
  84.  
  85. /**
  86. * 初始化参数。
  87. */
  88. private final void init() {
  89. mGettingBook = HandlerFactory.getNewHandlerInOtherThread("book");
  90. mDb = new DB(this);
  91. Cursor users = mDb.getAllUser();
  92. startManagingCursor(users);
  93. mAdapter = new SimpleCursorAdapter(this,
  94. android.R.layout.simple_spinner_item, users,
  95. new String[] { "username" }, new int[] { android.R.id.text1 });
  96. mAdapter
  97. .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  98. mSpinnerUser.setAdapter(mAdapter);
  99.  
  100. }
  101.  
  102. @OnClick(viewId = { R.id.home_scan, R.id.home_upload_result,
  103. R.id.home_borrow_book, R.id.home_return_book,
  104. R.id.home_user_manager })
  105. public void onButtonClick(View v) {
  106. switch (v.getId()) {
  107. case R.id.home_scan:
  108. Intent intent = new Intent("com.google.zxing.client.android.SCAN");
  109. this.startActivityForResult(intent, HOME_ACTIVITY);
  110. break;
  111. case R.id.home_upload_result:
  112. break;
  113. case R.id.home_borrow_book:
  114. break;
  115. case R.id.home_return_book:
  116. break;
  117. case R.id.home_user_manager:
  118. startActivity(new Intent(this, UserManagerActivity.class));
  119. break;
  120. default:
  121. break;
  122. }
  123. }
  124.  
  125. @Override
  126. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  127. if (requestCode != HOME_ACTIVITY) {
  128. super.onActivityResult(requestCode, resultCode, data);
  129. return;
  130. }
  131. if (data == null) {
  132. return;
  133. }
  134. final String isbn = data.getStringExtra("SCAN_RESULT");
  135. mTextScan.setText(String.format(mStringScan, isbn));
  136. if (isbn != null) {
  137. mTextBook.setText(mStringGetting);
  138. mGettingBook.post(new Runnable() {
  139.  
  140. @Override
  141. public void run() {
  142. DefaultHttpClient client = new DefaultHttpClient();
  143. HttpGet request = new HttpGet(DOUBAN_API + isbn);
  144. try {
  145. HttpResponse response = client.execute(request);
  146. book = XMLSax.sax(response.getEntity().getContent());
  147. String summary = book.getSummary();
  148. summary = summary.substring(0,
  149. summary.length() < 60 ? summary.length() : 60)
  150. .concat("...");
  151. String string = String.format(mStringBookInfo,
  152. book.getName(), book.getAuthor(),
  153. book.getPublisher(), book.getIsbn13(), summary);
  154. updateBookInfoView(string);
  155. } catch (Exception e) {
  156. e.printStackTrace();
  157. }
  158. }
  159.  
  160. });
  161. }
  162. }
  163.  
  164. /**
  165. * 更新图书信息
  166. *
  167. * @param string
  168. */
  169. private void updateBookInfoView(final String string) {
  170. runOnUiThread(new Runnable() {
  171. @Override
  172. public void run() {
  173. mTextBook.setText(string);
  174. }
  175. });
  176. }
  177.  
  178. @Override
  179. protected void onResume() {
  180. super.onResume();
  181. mAdapter.notifyDataSetChanged();
  182. }
  183.  
  184. @Override
  185. protected void onDestroy() {
  186. super.onDestroy();
  187. mDb.close();
  188. }
  189. }
/*
 * @(#)HomeActivity.java		       Project:bookscan
 * Date:2012-12-3
 *
 * Copyright (c) 2011 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sinaapp.msdxblog.bookscan.activity;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.sinaapp.msdxblog.androidkit.thread.HandlerFactory;
import com.sinaapp.msdxblog.androidkit.ui.ResBindUtil;
import com.sinaapp.msdxblog.androidkit.ui.UIBindUtil;
import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidRes;
import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidRes.ResType;
import com.sinaapp.msdxblog.androidkit.ui.annotation.AndroidView;
import com.sinaapp.msdxblog.androidkit.ui.annotation.OnClick;
import com.sinaapp.msdxblog.bookscan.R;
import com.sinaapp.msdxblog.bookscan.bean.Book;
import com.sinaapp.msdxblog.bookscan.util.DB;
import com.sinaapp.msdxblog.bookscan.util.XMLSax;

/**
 * @author Geek_Soledad ([email protected])
 */
public class HomeActivity extends Activity {
	private static final int HOME_ACTIVITY = 1990;
	private static final String DOUBAN_API = "http://api.douban.com/book/subject/isbn/";

	@AndroidView(id = R.id.home_result_scan)
	private TextView mTextScan;
	@AndroidView(id = R.id.home_book_info)
	private TextView mTextBook;
	@AndroidView(id = R.id.home_result_upload)
	private TextView mTextUpload;
	@AndroidView(id = R.id.home_users)
	private Spinner mSpinnerUser;

	@AndroidRes(id = R.string.result_scan, type = ResType.STRING)
	private String mStringScan;
	@AndroidRes(id = R.string.result_getting, type = ResType.STRING)
	private String mStringGetting;
	@AndroidRes(id = R.string.book_info, type = ResType.STRING)
	private String mStringBookInfo;

	private Handler mGettingBook;
	private Book book;
	private DB mDb;
	private SimpleCursorAdapter mAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		UIBindUtil.bind(this, R.layout.activity_home);
		ResBindUtil.bindAllRes(this);
		init();
	}

	/**
	 * 初始化参数。
	 */
	private final void init() {
		mGettingBook = HandlerFactory.getNewHandlerInOtherThread("book");
		mDb = new DB(this);
		Cursor users = mDb.getAllUser();
		startManagingCursor(users);
		mAdapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_spinner_item, users,
				new String[] { "username" }, new int[] { android.R.id.text1 });
		mAdapter
		.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mSpinnerUser.setAdapter(mAdapter);

	}

	@OnClick(viewId = { R.id.home_scan, R.id.home_upload_result,
			R.id.home_borrow_book, R.id.home_return_book,
			R.id.home_user_manager })
	public void onButtonClick(View v) {
		switch (v.getId()) {
		case R.id.home_scan:
			Intent intent = new Intent("com.google.zxing.client.android.SCAN");
			this.startActivityForResult(intent, HOME_ACTIVITY);
			break;
		case R.id.home_upload_result:
			break;
		case R.id.home_borrow_book:
			break;
		case R.id.home_return_book:
			break;
		case R.id.home_user_manager:
			startActivity(new Intent(this, UserManagerActivity.class));
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode != HOME_ACTIVITY) {
			super.onActivityResult(requestCode, resultCode, data);
			return;
		}
		if (data == null) {
			return;
		}
		final String isbn = data.getStringExtra("SCAN_RESULT");
		mTextScan.setText(String.format(mStringScan, isbn));
		if (isbn != null) {
			mTextBook.setText(mStringGetting);
			mGettingBook.post(new Runnable() {

				@Override
				public void run() {
					DefaultHttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(DOUBAN_API + isbn);
					try {
						HttpResponse response = client.execute(request);
						book = XMLSax.sax(response.getEntity().getContent());
						String summary = book.getSummary();
						summary = summary.substring(0,
								summary.length() < 60 ? summary.length() : 60)
								.concat("...");
						String string = String.format(mStringBookInfo,
								book.getName(), book.getAuthor(),
								book.getPublisher(), book.getIsbn13(), summary);
						updateBookInfoView(string);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			});
		}
	}

	/**
	 * 更新图书信息
	 * 
	 * @param string
	 */
	private void updateBookInfoView(final String string) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mTextBook.setText(string);
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mDb.close();
	}
}

 

你可能感兴趣的:(豆瓣)