2011年9月8日

Android: ZXing 使用Intent進行QR碼掃描

Simple access to barcode scanning in Android, via Intents:
ZXing 掃描QR條碼的程式庫

使用Intent呼叫ZXing來掃描QR碼
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);

接收掃描後結果
public void onActivityResult(int requestCode,int resultCode,Intent it) {
  if (requestCode == 0) {
     if (resultCode == RESULT_OK) {
        String contents = it.getStringExtra("SCAN_RESULT");
        String format = it.getStringExtra("SCAN_RESULT_FORMAT");
       // Handle successful scan
     } else if (resultCode == RESULT_CANCELED) {
      // Handle cancel
     }
  }
}

偵測是否已安裝 ZXing
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
if(getPackageManager().queryIntentActivities(intent,
   PackageManager.MATCH_DEFAULT_ONLY).size() == 0) {
    //未安裝,進行安裝
    //見底下程式碼.....
}

安裝ZXing Barcode Scanner
 AlertDialog.Builder downDg = new AlertDialog.Builder(myApp);
 downDg.setTitle("安裝Barcode Scanner");
 downDg.setMessage("程式需要ZXing Barcode Scanner,你要安裝嗎?");
 downDg.setPositiveButton("OK",new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialogInterface, int i) {
          Uri uri = Uri.parse(
            "market://search?q=pname:com.google.zxing.client.android");
          Intent intent = new Intent(Intent.ACTION_VIEW, uri);
          try {
                 startActivity(intent);
          } catch (ActivityNotFoundException anfe) {
                 // Hmm, market is not installed
          }
     }
 });
 downDg.setNegativeButton("取消", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialogInterface, int i) {}  });
 downDg.show();

沒有留言: