編輯:關於 Android 程式設計
最近專案需要用到二維碼的生成與辨識。網路上這方面的資源不少,其中 Google ZXing 對二維碼的封裝已經相當完整,可以直接取用。本文在官方範例的基礎上補上了長按辨識的功能——網路上雖然也有類似範例,但不少抓下來卻跑不起來,因此把可行版本整理在這裡。
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("")) {
// 依字串產生二維碼,第二個參數為圖片尺寸(350x350)
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();
// 用完務必關閉快取,否則會影響效能,且每次截到的都是同一張舊圖
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();
// 第一次只取寬高,不真正載入
options.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(bitmapPath, options);
// 用 inSampleSize 縮小取樣,才能真的省下記憶體
options.inSampleSize = options.outHeight / 400;
if (options.inSampleSize <= 0) {
options.inSampleSize = 1;
}
options.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(bitmapPath, options);
// 交給 ZXing 解析
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) {
// 辨識失敗時 result 保持 null
}
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 能讀的像素資料:
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;
@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;
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();
}
/** 掃描結果回呼 */
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 音量無法調整且偏吵,改用音樂流播放
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>
範例中已處理掉直拍解碼時二維碼被拉伸的問題。另外提醒兩點:掃描框調大之後辨識靈敏度反而會下降,這是取樣與畫面占比之間的取捨;而 view.setDrawingCacheEnabled(false) 那行不要省,否則除了效能受影響,長按辨識每次都會拿到同一張舊截圖。
最後,ZXing 屬於早期方案,近年的專案若只是要掃描或產生二維碼,可以考慮官方後續推出的 ML Kit 條碼掃描 API 或 JourneyApps 的 zxing-android-embedded,能省下不少自行維護 Camera 與 Handler 的成本。
Android 六種 AlertDialog 對話框的實作方式
App 只要需要與使用者互動,就離不開對話框。Android 中功能最完整、實務上最常用的是 AlertDialog,它能變化出多種內容形態。本文用六個可直接複用的範例,
用 GLSL 實作輝光(Glare / Glow)效果:原理、流程與 Shader
引言 GraphicsLab Project 立項之後,大部分時間都花在搭 Shader 實驗環境上。環境終於堪用,於是就拿它來做第一個實際效果——輝光。本文記錄在 Op
RxBinding 入門:用 RxJava 打造更直觀的 Android 事件綁定
近來重新整理 Rx 系列範例時,發現 RxBinding 是一個很值得投入的套件。它把 Android 常見的事件監聽,例如點擊、文字變更、焦點變化等,轉換成 RxJav
解決 ListView 項目點擊無回應的問題
在 ListView 中,如果項目布局內包含 Button、CheckBox 或其他可取得焦點的子控制項,整個項目可能無法正常接收點擊事件。這是因為子控制項搶走了焦點。