android二维码工程之仿QQ二维码实现

    二维码发展到现在几乎是每一个App都有的功能,之前项目里用到了二维码功能就研究了下如何嵌入zxing二维码工程,之前的用法制包含了最基本的二维码扫码工能,用QQ时看到QQd的扫一扫,功能相对较全,可以扫图片,可以开闪光灯,还可以生成二维码,都是比较常用的功能,于是就仿照QQ的二维码样式和功能,自己也做了一个common工程,这样,以后要用二维码是就不必再做配置等工作了,直接关联到这个二维码工程即可.文章最后我会将整个工程上传到我的资源中,有需要的可以下载。


    下面先看一下整体效果图:                                                                   点击相册后的效果图:         

    

    开灯后的效果图和设备串号生成的二维码:

   

  

     由于没有美工配合,样子真心是不如QQ好看,好在功能基本都实现了,相册就是从本地图库中选去二维码扫描,开灯就是打开手机闪光灯,二维码是将手机序列号生成一个二维码。下面是代码部分,改动的地方和添加的地方都做了注释,相信大家能看懂。‘

   1.相册功能添加代码,代码添加在zxing工程已有的CaptureActivity.java类中。

    相册点击事件处理:

	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.photo_btn:
			// 打开手机中的相册
			Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
			innerIntent.setType("image/*");
			Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
			this.startActivityForResult(wrapperIntent, REQUEST_CODE);
			break;
               }
     }

    利用zxing执行图片扫码:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK)
		{
			switch (requestCode)
			{
			case REQUEST_CODE:
				// 获取选中图片的路径
				Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
				if (cursor.moveToFirst())
				{
					photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
				}
				cursor.close();
				new Thread(new Runnable()
				{
					@Override
					public void run()
					{
						Result result = scanningImage(photo_path);
						if (result != null)
						{
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_SUC;
							m.obj = result.getText();
							mHandler.sendMessage(m);
						}
						else
						{
							Message m = mHandler.obtainMessage();
							m.what = PARSE_BARCODE_FAIL;
							m.obj = "Scan failed!";
							mHandler.sendMessage(m);
						}
					}
				}).start();

				break;

			}
		}
	}
    scanneringImage()方法代码:
/**
	 * 扫描二维码图片的方法
	 * 
	 * @param path
	 * @return
	 */
	public Result scanningImage(String path)
	{
		if (TextUtils.isEmpty(path))
		{
			return null;
		}
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // 设置二维码内容的编码

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 先获取原大小
		scanBitmap = BitmapFactory.decodeFile(path, options);
		options.inJustDecodeBounds = false; // 获取新的大小
		int sampleSize = (int) (options.outHeight / (float) 200);
		if (sampleSize <= 0)
			sampleSize = 1;
		options.inSampleSize = sampleSize;
		scanBitmap = BitmapFactory.decodeFile(path, options);
		RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		try
		{
			return reader.decode(bitmap1, hints);

		}
		catch (NotFoundException e)
		{
			e.printStackTrace();
		}
		catch (ChecksumException e)
		{
			e.printStackTrace();
		}
		catch (FormatException e)
		{
			e.printStackTrace();
		}
		return null;
	}
   2.开闪光灯,下面是开闪光灯要添加的代码,代码添加在CameraManager.java中。

	/**
	 * 通过设置Camera打开闪光灯
	 */
	public void turnLightOn()
	{
		if (camera == null)
		{
			return;
		}
		Parameters parameters = camera.getParameters();
		if (parameters == null)
		{
			return;
		}

		List<String> flashModes = parameters.getSupportedFlashModes();
		if (flashModes == null)
		{
			return;
		}
		String flashMode = parameters.getFlashMode();
		Log.i(TAG, "Flash mode: " + flashMode);
		Log.i(TAG, "Flash modes: " + flashModes);
		// 闪光灯关闭状态
		if (!Parameters.FLASH_MODE_TORCH.equals(flashMode))
		{
			// Turn on the flash
			if (flashModes.contains(Parameters.FLASH_MODE_TORCH))
			{
				parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
				camera.setParameters(parameters);
				camera.startPreview();
			}
			else
			{
			}
		}
	}

	/**
	 * 通过设置Camera关闭闪光灯 
	 * @param mCamera
	 */
	public void turnLightOff()
	{
		if (camera == null)
		{
			return;
		}
		Parameters parameters = camera.getParameters();
		if (parameters == null)
		{
			return;
		}
		List<String> flashModes = parameters.getSupportedFlashModes();
		String flashMode = parameters.getFlashMode();
		// Check if camera flash exists
		if (flashModes == null)
		{
			return;
		}
		// 闪光灯打开状态
		if (!Parameters.FLASH_MODE_OFF.equals(flashMode))
		{
			// Turn off the flash
			if (flashModes.contains(Parameters.FLASH_MODE_OFF))
			{
				parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
				camera.setParameters(parameters);
			}
			else
			{
				Log.e(TAG, "FLASH_MODE_OFF not supported");
			}
		}
	}
  3.生成二维码,代码添加在CaptureActivity.java类中。

/***
	 * 获得手机设备的串号
	 * @param context
	 * @return
	 */
	public static String getIMEI(Context context)
	{
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		// Get deviceId
		String deviceId = tm.getDeviceId();
		// If running on an emulator
		if (deviceId == null || deviceId.trim().length() == 0 || deviceId.matches("0+"))
		{
			deviceId = (new StringBuilder("EMU")).append((new Random(System.currentTimeMillis())).nextLong())
					.toString();
		}
		return deviceId;
	}

     /**
      * 生成二维码方法
      */
     private Bitmap createQRCode()
    {
        int QR_WIDTH = 100;
        int QR_HEIGHT = 100;

        try
        {
            // 需要引入core包
            QRCodeWriter writer = new QRCodeWriter();

            String mime= getIMEI(this);
            if (text == null || "".equals(text) || text.length() < 1)
            {
                return null;
            }

            // 把输入的文本转为二维码
            BitMatrix martix = writer.encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT);

            System.out.println("w:" + martix.getWidth() + "h:" + martix.getHeight());

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            for (int y = 0; y < QR_HEIGHT; y++)
            {
                for (int x = 0; x < QR_WIDTH; x++)
                {
                    if (bitMatrix.get(x, y))
                    {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    }
                    else
                    {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }

                }
            }

            // cheng chen de er wei ma
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);

            return bitmap;
        }
        catch (WriterException e)
        {
            e.printStackTrace();
        }
        return null;
    }

  初始工程的配置和对扫描框的修改都参考了这篇博客,大家可以看下。http://blog.csdn.net/xiaanming/article/details/10163203.

 项目源码

 

 

发布了66 篇原创文章 · 获赞 59 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章