編輯:關於 Android 程式設計
這款 App 在 360 平台上線一個月,下載量就突破了一千多次。這裡把程式碼全部分享出來,供大家學習參考,還會順帶教你如何接入廣告賺點零花。首先介紹這款應用:它是一個二維碼生成器。雖然網上關於製作二維碼的教學很多,我這裡就再嘮叨一遍,並把所有功能模組的程式碼都分享出來。
這裡我們需要一個輔助類 RGBLuminanceSource,Google 官方也提供了這個類,我們直接複製過來就能用:
package com.njupt.liyao; import com.google.zxing.LuminanceSource; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.FileNotFoundException; public final class RGBLuminanceSource extends LuminanceSource { private final byte[] luminances; public RGBLuminanceSource(String path) throws FileNotFoundException { this(loadBitmap(path)); } public RGBLuminanceSource(Bitmap bitmap) { super(bitmap.getWidth(), bitmap.getHeight()); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); // In order to measure pure decoding speed, we convert the entire image // to a greyscale array // up front, which is the same as the Y channel of the // YUVLuminanceSource in the real app. luminances = new byte[width * height]; for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { int pixel = pixels[offset + x]; int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = pixel & 0xff; if (r == g && g == b) { // Image is already greyscale, so pick any channel. luminances[offset + x] = (byte) r; } else { // Calculate luminance cheaply, favoring green. luminances[offset + x] = (byte) ((r + g + g + b) >> 2); } } } } @Override public byte[] getRow(int y, byte[] row) { if (y < 0 || y >= getHeight()) { throw new IllegalArgumentException( "Requested row is outside the image:"+ y); } int width = getWidth(); if (row == null || row.length < width) { row = new byte[width]; } System.arraycopy(luminances, y * width, row, 0, width); return row; } // Since this class does not support cropping, the underlying byte array // already contains // exactly what the caller is asking for, so give it to them without a copy. @Override public byte[] getMatrix() { return luminances; } private static Bitmap loadBitmap(String path) throws FileNotFoundException { Bitmap bitmap = BitmapFactory.decodeFile(path); if (bitmap == null) { throw new FileNotFoundException("Couldn't open"+ path); } return bitmap; } } 接著是生成二維碼的核心方法,透過 ZXing 的 QRCodeWriter 把文字編碼成圖形:
public Bitmap getTwoDimensionPicture(String text,int width,int height) throws WriterException{ if(text.equals("")) { text=""; } Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET,"utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); int []pixels = new int[width*height]; for(int y=0;y<height;y++){ for(int x=0;x<width;x++){ if (bitMatrix.get(x, y)) { pixels[y * width + x] = BLACK; } else { pixels[y * width + x] = WHITE; } } } Bitmap bitmap=Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0,width, 0, 0, width, height); return bitmap; } 生成後若要保存到 SD 卡,並同步顯示在系統圖庫,可以這樣做:
public void createDirctoryToSaveImage(){ String dirPath=Environment.getExternalStorageDirectory()+File.separator+"TowDimensionCode"; File dirFile=new File(dirPath); if(!dirFile.exists()){ dirFile.mkdir(); } } public void writeBitMapToSDCard(Bitmap bitmap) throws IOException{ String fname = DateFormat.format("yyyyMMddhhmmss", new Date()).toString()+".jpg"; String filePath=Environment.getExternalStorageDirectory()+File.separator+"TowDimensionCode" +File.separator+fname; File file=new File(filePath); FileOutputStream fileOutputStream=new FileOutputStream(file); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); //把圖片加入到系統圖庫裡面 MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), file.getAbsolutePath(), fname, null); //uri得到的是文件的絕對路徑 getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+file.getAbsolutePath()))); edtText.setText(file.getAbsolutePath()); Toast.makeText(this,"生成成功", Toast.LENGTH_LONG).show(); } 如果要從相冊中選取圖片進行辨識,可以透過 Intent 調用系統相冊:
//打開相冊 private void setImage() { //使用intent調用系統提供的相冊功能,使用startActivityForResult是為了獲取用戶選擇的圖片 Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT); getAlbum.setType(IMAGE_TYPE); startActivityForResult(getAlbum, IMAGE_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data){ if (resultCode != RESULT_OK) { //此處的 RESULT_OK 是系統自定義得一個常量 Log.e("TAG->onresult","ActivityResult resultCode error"); return; } Bitmap bm = null; //外界的程序訪問ContentProvider所提供數據 可以通過ContentResolver接口 ContentResolver resolver = getContentResolver(); //此處的用於判斷接收的Activity是不是你想要的那個 if (requestCode == IMAGE_CODE) { try { Uri originalUri = data.getData(); //獲得圖片的uri bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); //顯得到bitmap圖片 imgView.setImageBitmap(bm); //這裡開始的第二部分,獲取圖片的路徑: String[] proj = {MediaColumns.DATA}; //好像是android多媒體數據庫的封裝接口,具體的看Android文檔 Cursor cursor = managedQuery(originalUri, proj, null, null, null); //按我個人理解 這個是獲得用戶選擇的圖片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); //將光標移至開頭 ,這個很重要,不小心很容易引起越界 cursor.moveToFirst(); //最後根據索引值獲取圖片路徑 String path = cursor.getString(column_index); edtText.setText(path); btnOpen.setText(R.string.recognitionTwoCode); }catch (IOException e) { Log.e("TAG-->Error",e.toString()); } } } 解析二維碼圖片內容的方法如下:
/** * 解析二維碼圖片裡的內容 * @param filePath 二維碼圖片的位置 * @throws IOException * @throws NotFoundException */ private String readImage(ImageView imageView) { String content = null; Map<DecodeHintType, String> hints = new HashMap<DecodeHintType, String>(); hints.put(DecodeHintType.CHARACTER_SET,"utf-8"); // 獲得待解析的圖片 Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); RGBLuminanceSource source = new RGBLuminanceSource(bitmap); BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source)); QRCodeReader reader = new QRCodeReader(); try { Result result = reader.decode(bitmap1, hints); // 得到解析後的文字 content = result.getText(); } catch (Exception e) { e.printStackTrace(); } return content; } 最後是接入廣告的部分,這裡以某廣告平台為例:
//ad布局部分 private RelativeLayout adContainer = null; private IMvBannerAd bannerad = null; final String adSpaceid ="這是你申請的廣告ID號"; adContainer=(RelativeLayout)findViewById(R.id.adcontent); bannerad = Mvad.showBanner(adContainer, this, adSpaceid, false); bannerad.showAds(this);
以上就是這款下載量破千的 Android 二維碼生成器 App 的完整源碼,涵蓋生成、保存、相冊辨識與廣告接入,別錯過啦!
【React Native 開發】DrawerLayoutAndroid 抽屜導航切換組件講解(13)
(一)前言 今天我們一起來看一下抽屜 DrawerLayoutAndroid 導航切換控件的講解與基本使用。 該 DrawerLayoutAndroid 組件封裝了 An
手機 MPT 模式和 USB 調試模式有什麼區別?
在手機與電腦的連接方式清單裡,常會看到一個叫 MPT 的選項。它到底是什麼?和開發者熟悉的 USB 調試模式又有何差異? 手機 MPT 模式是什麼? MPT 模式
Android 仿微信選單欄:ViewPager 與底部 Tab 切換實作
本文示範如何以 ViewPager 搭配自訂底部選單,做出類似微信的頂部與底部選單切換效果。整體思路是將每個分頁對應一個 XML 布局,當使用者左右滑動或點擊底部按鈕時,
Android 二維碼開源專案 ZXing 的編譯與踩坑記錄
ZXing 是一個開放原始碼、以 Java 實作的多格式 1D/2D 條碼圖像處理庫,並有對應其他語言的移植版本。它能呼叫手機內建相機完成條碼掃描與解碼,同時支援條碼的編