- 到 https://code.google.com/p/zxing/ 下載
com.google.zxing.integration.android.IntentIntegrator
com.google.zxing.integration.android.IntentResult
兩個類的源碼放到自己工程中 -
集成
-
在
Activity
類的要調用掃描程序的地方添加以下代碼IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.initiateScan();
-
Activity
類實現onActivityResult
方法 -
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
-
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
-
if (scanResult != null) {
-
String contents = scanResult.getContents();
-
// 對掃描內容處理
-
} else {
-
textView.setText("error");
-
}
-
}
-
二維碼的應用是越來越廣呢。我們會收到在手機上掃描二維碼的需求,那麼,我們嘗試使用一種方法實現。
前置:
需要第三方APK。名稱是 “條碼掃描器” ,該APK在 google play 和豌豆莢市場都能夠下載到。
過程:
1,開始掃描二維碼
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);//指定當前的activityintegrator.initiateScan(IntentIntegrator.QR_CODE_TYPES); //啓動掃描
2,註冊掃描完成後的處理(回調)
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode, intent);if (result != null) {String contents = result.getContents();if (contents != null) {showDialog(R.string.result_succeeded, result.toString());} else {showDialog(R.string.result_failed,getString(R.string.result_failed_why));}}}3,完成。。。
那麼我們需要上面提到的類 IntentIntegrator ,從哪裏來的? 我是從 google開源的項目zxing裏代碼裏找到的。並提取了一些代碼來使用。我會在本文的末尾提供代碼下載,可以從代碼裏獲得這個類。
----------------------
擴展閱讀
恩。那麼 IntentIntegrator 這個類裏到底幹了什麼?
通過閱讀代碼,我們知道它做了兩件事:
1.查找目標APK 裏 “是否有掃描二維碼的程序”。如果不存在,那麼提示,並使得指示用戶 去市場下載。
2.如果存在,發送intent。發送了,那麼會有 相應的Activity來處理它,在activty關閉後 封裝對應的返回參數。
建議大家去讀讀zxing的代碼。
-
public
void onActivityResult(int
requestCode,
int resultCode,
Intent intent)
{
IntentResult
scanResult =
IntentIntegrator.parseActivityResult(requestCode,
resultCode, intent);
if
(scanResult
!=
null)
{
String
contents = scanResult.getContents();
//
對掃描內容處理
}
else
{
textView.setText("error");
}
}