ปัจจุบันนี้เรื่องของ Bar Code และ QR Code จะให้ว่ามีอยู่มากมายในการใช้ชีวิตของเรา ไม่ว่าจะเป็นการแอดเพื่อนใน Application Line หรือ การจ่ายเงินด้วย การแสกน QR Code ทุกอย่างเหล่านี้ สามารถทำได้อย่างง่ายดายด้วยการสแกน QR Code เพื่ออำนวยความสะดวกให้กับผู้ใช้งานให้ได้มากที่สุด
ทีนี้เราลองมาดูวิธีการเขียนแอพ Android เพื่อใช้ในการสแกน QR Code และ Bar Code Reader กันดูบ้างครับ
การที่เราจะเขียนแอพที่ใช้งานเกี่ยวกับการสแกน QR Code บน Android นั้นทาง Google ได้มี com.google.zxing เพื่อให้เราเรียกใช้งาน Feature ในการสแกน QR Code ขึ้นมาให้แล้วครับ
1. อันดับแรก เปิด Android Studio ขึ้นมาแล้วทำการสร้าง Blank Activity ให้เรียบร้อยครับ 2. เปิด activity_main.xml ขึ้นมาแล้วทำการกำหนดโค้ดตามนี้ครับจะเห็นได้ว่า มีในส่วนของ Text และ Button ขึ้นมาครับ
โค้ด: เลือกทั้งหมด
<RealtiveLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://chemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
tools:context=".Mainactivity">
<TextView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text=@"Result : "
android:textAppearance="?android:attr/textAppearanceLarge"
anroid:layout_centerHorizontal="true"
android:id="@+id/textResult" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_parent"
android:id="@+id/btnScan"
android:text=@"Scan"
android:layout_below:"@+id/txtResult"
android:layout_alignParentStart="true"
android:layout_marginTop="98dp" />
</RealtiveLayout>
โค้ด: เลือกทั้งหมด
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
โค้ด: เลือกทั้งหมด
public class ReadQRCodeActivity extends Activity {
private Button btnScan;
private TextView txtResult;
}
โค้ด: เลือกทั้งหมด
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnScan = (Button)findViewById(R.id.btnScan);
txtResult = (TextView)findViewById(R.id.txtResult);
}
โค้ด: เลือกทั้งหมด
btnScan.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//TODO Auto-generated method stub
try{
Intent intentOption = new Intent("com.google.zxing.client.android.SCAN");
intentOption.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent,0);
} catch(Exception e){
//TODO handle exception
Toast.makeText(getBaseContext(),"Please Install Barcode Scanner",Toast.LENGTH_SHORT).show();
}
}
});
โค้ด: เลือกทั้งหมด
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// TODO Auto-generated method stub
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
txtResult.setText("Result : " + contents);
}
}
}