編輯:Android 開發實例
最近專案需要用到二維碼的生成與辨識。上網搜尋後發現這方面的資源相當豐富,其中 Google ZXing 對二維碼的封裝已經相當成熟,可以直接取用。以下範例在官方 Demo 的基礎上做了少量改動,主要是加入「長按辨識螢幕上的二維碼」功能——網上雖然也有長按辨識的範例,但不少下載回來卻跑不起來,這裡把可用的版本整理出來。
public class BarCodeTestActivity extends Activity {
private TextView resultTextView;
private EditText qrStrEditText;
private ImageView qrImgImageView;
private String time;
private File file = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultTextView = (TextView) this.findViewById(R.id.tv_scan_result);
qrStrEditText = (EditText) this.findViewById(R.id.et_qr_string);
qrImgImageView = (ImageView) this.findViewById(R.id.iv_qr_image);
Button scanBarCodeButton = (Button) this.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);
}
});
qrImgImageView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// 長按識別二維碼
saveCurrentImage();
return true;
}
});
Button generateQRCodeButton = (Button) this.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();
}
}
});
}
// 截取目前畫面並保存為圖片
private void saveCurrentImage() {
// 獲取當前屏幕的大小
int width = getWindow().getDecorView().getRootView().getWidth();
int height = getWindow().getDecorView().getRootView().getHeight();
// 生成相同大小的圖片
Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// 找到當前頁面的根佈局
View view = getWindow().getDecorView().getRootView();
// 設置緩存
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
// 從緩存中獲取當前屏幕的圖片
temBitmap = view.getDrawingCache();
SimpleDateFormat df = new SimpleDateFormat("yyyymmddhhmmss");
time = df.format(new Date());
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/screen", time + ".png");
if (!file.exists()) {
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
temBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/screen/" + time + ".png";
final Result result = parseQRcodeBitmap(path);
runOnUiThread(new Runnable() {
public void run() {
if (null != result) {
resultTextView.setText(result.toString());
} else {
Toast.makeText(BarCodeTestActivity.this,
"無法識別", Toast.LENGTH_LONG).show();
}
}
});
}
}).start();
// 禁用 DrawingCache 否則會影響性能
view.setDrawingCacheEnabled(false);
}
}
// 解析二維碼圖片,返回結果封裝在 Result 對象中
private com.google.zxing.Result parseQRcodeBitmap(String bitmapPath) {
// 解析轉換類型 UTF-8
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
BitmapFactory.Options options = new BitmapFactory.Options();
// 若把 inJustDecodeBounds 設為 true,
// decodeFile 並不會真的返回 Bitmap,只會把寬高帶回來
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
// 此時 bitmap 為 null,但 options.outWidth / outHeight 已是我們想要的寬高
// 用 inSampleSize 進行取樣縮小,才能真正節約記憶體
options.inSampleSize = options.outHeight / 400;
if (options.inSampleSize <= 0) {
options.inSampleSize = 1; // 防止其值小於或等於 0
}
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(bitmapPath, options);
// 新建一個 RGBLuminanceSource 對象,將 bitmap 圖片傳給此對象
RGBLuminanceSource rgbLuminanceSource = new RGBLuminanceSource(bitmap);
// 將圖片轉換成二進制圖片
BinaryBitmap binaryBitmap =
new BinaryBitmap(new HybridBinarizer(rgbLuminanceSource));
// 初始化解析對象
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(binaryBitmap, hints);
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
@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);
}
}
}
ZXing 內建的亮度來源多為相機預覽設計,若要解析「已經在畫面上或存在檔案中的圖片」,需要自己實作一個 LuminanceSource。長按辨識正是靠這個類別:
public class RGBLuminanceSource extends LuminanceSource {
private byte bitmapPixels[];
protected RGBLuminanceSource(Bitmap bitmap) {
super(bitmap.getWidth(), bitmap.getHeight());
// 首先,要取得該圖片的像素數組內容
int[] data = new int[bitmap.getWidth() * bitmap.getHeight()];
this.bitmapPixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(data, 0, getWidth(), 0, 0, getWidth(), getHeight());
// 將 int 數組轉換為 byte 數組
for (int i = 0; i < data.length; i++) {
this.bitmapPixels[i] = (byte) data[i];
}
}
@Override
public byte[] getMatrix() {
// 返回我們生成好的像素數據
return bitmapPixels;
}
@Override
public byte[] getRow(int y, byte[] row) {
// 這裡要得到指定行的像素數據
System.arraycopy(bitmapPixels, y * getWidth(), row, 0, getWidth());
return row;
}
}
public class CaptureActivity extends Activity implements Callback {
private CaptureActivityHandler handler;
private ViewfinderView viewfinderView;
private boolean hasSurface;
private Vector<BarcodeFormat> decodeFormats;
private String characterSet;
private InactivityTimer inactivityTimer;
private MediaPlayer mediaPlayer;
private boolean playBeep;
private static final float BEEP_VOLUME = 0.10f;
private boolean vibrate;
private Button cancelScanButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
CameraManager.init(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
cancelScanButton = (Button) this.findViewById(R.id.btn_cancel_scan);
hasSurface = false;
inactivityTimer = new InactivityTimer(this);
}
@Override
protected void onResume() {
super.onResume();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
initCamera(surfaceHolder);
} else {
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
decodeFormats = null;
characterSet = null;
playBeep = true;
AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
playBeep = false;
}
initBeepSound();
vibrate = true;
// quit the scan view
cancelScanButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CaptureActivity.this.finish();
}
});
}
@Override
protected void onPause() {
super.onPause();
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
CameraManager.get().closeDriver();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
/**
* 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);
this.setResult(RESULT_OK, resultIntent);
}
CaptureActivity.this.finish();
}
private void initCamera(SurfaceHolder surfaceHolder) {
try {
CameraManager.get().openDriver(surfaceHolder);
} catch (IOException ioe) {
return;
} catch (RuntimeException e) {
return;
}
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { }
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
public ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
private void initBeepSound() {
if (playBeep && mediaPlayer == null) {
// STREAM_SYSTEM 的音量無法調整,使用者反映太吵,
// 因此改在 music stream 上播放
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(beepListener);
AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException e) {
mediaPlayer = null;
}
}
}
private static final long VIBRATE_DURATION = 200L;
private void playBeepSoundAndVibrate() {
if (playBeep && mediaPlayer != null) {
mediaPlayer.start();
}
if (vibrate) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(VIBRATE_DURATION);
}
}
/** 提示音播放完畢後,倒回以便下次再播 */
private final OnCompletionListener beepListener = new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
}
};
}
<?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:textSize="18sp"
android:textColor="@android:color/black"
android:layout_height="wrap_content" />
</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="250dp"
android:layout_height="250dp"
android:scaleType="fitXY"
android:layout_marginTop="10dp"
android:layout_gravity="center"/>
</LinearLayout>
更完整的細節請下載 Demo 自行參考,其中也處理了直拍解碼時二維碼被拉伸的問題。
作者自己也提到一個現象:掃描框調大之後,辨識靈敏度反而下降。原因通常是取樣與縮圖的關係——框越大,送入解碼器的影像區域越大,若解析度沒跟著提高,模組(module)的像素數反而不足,對位圖案就難以對齊。改善方向是提高相機解析度、縮小 inSampleSize,並在 decodeFormats 中只保留需要的格式以減少誤判。
另外兩點務必留意:一是 saveCurrentImage() 用到 DrawingCache 與外部儲存,新版 Android 需要動態請求 WRITE_EXTERNAL_STORAGE 或改用 getExternalFilesDir();二是相機相關 API(android.hardware.Camera)在新版系統已不建議使用,新專案請直接採用 ZXing 官方後續維護的 zxing-android-embedded 或 CameraX,可省下大量相容性處理。
Android 登入實作:帳號密碼驗證與三次錯誤鎖定
登入畫面負責向使用者索取帳號與密碼以驗證身分,是許多應用(如 Facebook、微博)的必備環節。本章說明如何建立登入介面,並處理安全性與錯誤嘗試次數的限制。 首先在版
Android 的 Style 與 Theme:一次搞懂主題與樣式的分層設計
現在幾乎每家公司都會在 Android 上部署自己的客戶端,而使用者對介面美觀度的期待也越來越高。Style 與 Theme 就是 Android 用來統一視覺風格、提升
ViewPager實現左右無限循環滑動與滑動跳轉
前一篇講了如何用 ViewPager 高仿 launcher 的拖動效果,之後不少朋友來問:能不能實現左右循環滑動和引導頁?今天就把左右滑動做出來了。至於「滑到最後一頁再
Android 多媒體播放:MediaPlayer 控制音樂
Android 的 MediaPlayer 類別可以控制音訊與影片播放。開發者可以透過它實作播放、暫停、快轉、倒退與音量控制等功能。 建立 MediaPlayer 將音樂