2013年6月18日 星期二

Android App 讀取及產生 QR-Code (二)

使用 QR-Droid 產生 QR-Code

為什麼使用 QR-Droid 呢?只是想跟別人不一樣... XD...

繼續 Android App 讀取及產生 QR-Code (一) ,這篇是說明 QR-Droid 產生 QR Code 圖檔在 Local Storage。

範例:

    點 Generate 按鈕,將資料 pass 給 QR-Droid,請 QR-Droid 代為產生 QR Code,在 ImageView 顯示 QR-Code 圖形。

1. 開啟 QR-Droid Activity,請 QR-Droid 產生 QR-Code 圖檔
    String qrContent = "myown://category_1?name=john&time=06-19";
    final String encodeUrl = URLEncoder.encode(qrContent);  //如果要轉換QRCode的內容有特殊符號或中文,記得 encode。

    ... 在 Button 的 onClickListener加入以下動作 ...

    Intent i = new Intent("la.droid.qr.encode");   //使用QRDroid的產生QRCode功能
    i.putExtra("la.droid.qr.code", encodeUrl);     //指定 QR Code 內容 encodeUrl
    i.putExtra( "la.droid.qr.size" , 200);         //指定 QR Code image 大小
    i.putExtra( "la.droid.qr.image" , true);       //指定 QR Code image 產生在 local storage (SDCard),若沒指定,會產生在 remote,回傳會是一個 image URL。
           
    try {
        //請 QRDroid App 產生一個 QRCode 
        startActivityForResult(i, 0);
           
    } catch(ActivityNotFoundException ex) {
           
        //若沒安裝 QRDroid,則開啟 Google Play商店,並顯示 QRDroid App 
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=la.droid.qr"));
        startActivity(intent);
    }
2. 實作 onActivityResult,QR-Droid 掃描結果會 call back onActivityResult 方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if( 0==requestCode && null!=data && data.getExtras()!=null ) {
            //產生的QRCode Image 路徑,存放在 key 為 la.droid.qr.result 的值中
            String qrcodeImgPath = data.getExtras().getString("la.droid.qr.result");
            Uri imgPath = Uri.fromFile(new File(qrcodeImgPath));
            mQRCodeImg.setImageURI(imgPath);
        }
    }


沒有留言: