此專案要透過ZXing Library建構 QR Code Scanner。
因此需先載入相關的函式庫,開啟Android Studio中的buid.gradle。
在buid.gradle 中找到 dependencies 後添加下列資料,後編譯專案即可成功載入函式庫。
compile 'com.google.zxing:core:3.2.1'
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
於Layout中添加按鈕以利觸發掃描行為。此案例將按鈕的傾聽事件方法名稱設為onClickScanQR。
以下為 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.developer.lungyu.ncyu_agricultural.SplashActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickScanQR"
android:id="@+id/QR_Code_Scan"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:layout_marginTop="24dp" />
</RelativeLayout>
並添加以下程式碼至 MainActivity.java。
onClickScanQR為觸發後執行之行為。
onActivityResult為掃描完畢後回傳之資料。
public void onClickScanQR(View v){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result !=null){
if(result.getContents() == null){
Toast.makeText(this,"You can't celled the scanning",Toast.LENGTH_SHORT).show();;
}else {
Toast.makeText(this,result.getContents(),Toast.LENGTH_SHORT).show();
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
文章標籤
全站熱搜