編輯:Android 技術基礎
項目裡需要二維碼能力時,不必自己從零造輪子。Google 開源的 ZXing 是事實上的標準方案,條形碼與二維碼的掃描、生成都覆蓋到了。原理上兩者有點差別:掃描條形碼基本就是直接讀出編碼內容,而二維碼則可以自定義編碼格式,按需編解碼。
源碼可從 https://code.google.com/p/zxing/ 獲取,按官方文檔接入即可。本文使用的是精簡過的版本,刪去了一般場景用不到的文件,工程結構大致如下:

其中 encoding 包是自行補上的,功能是傳入一段字符串、生成對應的二維碼圖片並返回 Bitmap;其餘各包均來自 ZXing 原項目。掃描界面也做了改動:官方默認是橫向的,這裡改為縱向,並在頂部加了 Tab 與取消按鈕(camera.xml)。此外還需要 colors.xml、ids.xml 等資源文件,以及 libs 下的 jar 包。
左圖是根據輸入字符串生成的二維碼,右圖是掃描後在界面上顯示結果:

點擊 Open Camera 打開掃描框(左圖),掃描條形碼的結果如下(右圖):

把 ZXing 項目中的相關文件複製到自己的工程,然後在 Manifest 中聲明相機與震動權限:
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
掃描界面需要全屏橫屏鎖定(此處改為 portrait)、隱藏軟鍵盤:
<activity
android:configChanges="orientation|keyboardHidden"
android:name="com.zxing.activity.CaptureActivity"
android:screenOrientation="portrait"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
上半部分放掃描入口與結果展示,下半部分放二維碼生成的輸入框與預覽:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical">
<Button
android:id="@+id/btn_scan_barcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="Open camera" />
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textSize="18sp"
android:text="Scan result:" />
<TextView
android:id="@+id/tv_scan_result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/black" />
</LinearLayout>
<EditText
android:id="@+id/et_qr_string"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:hint="Input the text" />
<Button
android:id="@+id/btn_add_qrcode"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate QRcode" />
<ImageView
android:id="@+id/iv_qr_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center" />
</LinearLayout>
打開掃描框、展示掃描結果、根據輸入生成二維碼,都在同一個 Activity 中完成:
public class BarCodeTestActivity extends Activity {
private TextView resultTextView;
private EditText qrStrEditText;
private ImageView qrImgImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultTextView = (TextView) findViewById(R.id.tv_scan_result);
qrStrEditText = (EditText) findViewById(R.id.et_qr_string);
qrImgImageView = (ImageView) findViewById(R.id.iv_qr_image);
// 打開掃描界面
Button scanBarCodeButton = (Button) findViewById(R.id.btn_scan_barcode);
scanBarCodeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent openCameraIntent = new Intent(BarCodeTestActivity.this, CaptureActivity.class);
startActivityForResult(openCameraIntent, 0);
}
});
// 根據字符串生成二維碼
Button generateQRCodeButton = (Button) findViewById(R.id.btn_add_qrcode);
generateQRCodeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
String contentString = qrStrEditText.getText().toString();
if (!contentString.equals("")) {
// 第二個參數為圖片尺寸 350*350
Bitmap qrCodeBitmap = EncodingHandler.createQRCode(contentString, 350);
qrImgImageView.setImageBitmap(qrCodeBitmap);
} else {
Toast.makeText(BarCodeTestActivity.this,
"Text can not be empty", Toast.LENGTH_SHORT).show();
}
} catch (WriterException e) {
e.printStackTrace();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 處理掃描結果
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String scanResult = bundle.getString("result");
resultTextView.setText(scanResult);
}
}
}
EncodingHandler 是我們在 ZXing 基礎上補上的一層,做法是用 MultiFormatWriter 編碼出 BitMatrix,再逐像素轉成 Bitmap:
public final class EncodingHandler {
private static final int BLACK = 0xff000000;
public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix matrix = new MultiFormatWriter().encode(str,
BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
int width = matrix.getWidth();
int height = matrix.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (matrix.get(x, y)) {
pixels[y * width + x] = BLACK;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
}
指定 CHARACTER_SET 為 utf-8 是必要的一步,否則包含中文的內容會出現亂碼。
掃描完成後,ZXing 會呼叫 CaptureActivity 中的 handleDecode。自定義業務邏輯就寫在這裡:
/**
* Handler scan result
*/
public void handleDecode(Result result, Bitmap barcode) {
inactivityTimer.onActivity();
playBeepSoundAndVibrate();
String resultString = result.getText();
if (resultString.equals("")) {
Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
} else {
Intent resultIntent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("result", resultString);
resultIntent.putExtras(bundle);
setResult(RESULT_OK, resultIntent);
}
finish();
}
在真實項目中,這裡通常不會只是把字符串顯示出來,而是據內容做分發:是鏈接就跳轉瀏覽器,是名片信息就寫入聯繫人,是自家協議格式就交給業務層解析。
ZXing 的接入成本並不高,工作量集中在三處:拷貝並裁剪源碼、調整掃描界面適配自己的設計、在 handleDecode 中接入業務。生成能力則靠一個幾十行的 EncodingHandler 補齊,掃描與生成兩端就都能自給自足了。
Matrix 圖形變換:set、post、pre 的差別與放大三倍實作(從零開始學 Android)
Matrix 就是線性代數裡的矩陣。在 Android 繪圖體系中,它負責圖形的平移、旋轉、縮放與傾斜——這也正是很多人當初學微積分、線代時覺得「以後絶対用不到」的那塊知
Android 調用 WebService 完整實戰
本節引言 經過前面的學習,數據請求、數據解析、文件上傳下載等内容,應該已經能滿足大家與服務器交互的基本需求了。本節要介紹的是 Android 調用 WebService。
底部導航加 ViewPager:打造可滑動切換的 Fragment 頁面
從底部導航到可滑動頁面前三篇使用不同方式完成底部導航後,可以進一步加入 ViewPager,讓使用者除了點擊底部選單,也能以左右滑動切換頁面。這種做法在內容型 App 中
Date & Time 組件(上):TextClock、AnalogClock 與 Chronometer
本節引言: 這一節介紹幾個用來顯示時間的 Android 原生控件:TextClock、AnalogClock 和 Chronometer(至於已經過時的 Digital