网上有很多关于二维码扫码和二维码生成的Demo,你可能不想透彻的了解它是如何实现的,但是你必须要知道如何引入到你的项目之中,我们研究一下如何将这些Demo引入到自己的项目之中。
我也写了一个Demo,看一下它的目录结构。
这些打红色箭头的部分都是必须要复制到你的项目之中的。引入到你的项目之后会有一些报错,你可以根据错误提示进行修改。
strings里面有一个字段要加入到你的项目之中
colors.xml中有一些你也要复制过去,还好他们都会报错提醒你。
下面我们看一下Demo的代码:
1.MainActivity.java:
package com.example.scancodedemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener { public static final int CODE=1; private Button mScanCode; private Button mCreateCode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mCreateCode=(Button)findViewById(R.id.btn_create_code); mScanCode=(Button)findViewById(R.id.btn_scan_code); mCreateCode.setOnClickListener(this); mScanCode.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_create_code: Intent intent1=new Intent(MainActivity.this,CodeShowActivity.class); startActivity(intent1); break; case R.id.btn_scan_code: Intent intent=new Intent(MainActivity.this,MipcaActivityCapture.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivityForResult(intent, CODE); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case CODE: if(resultCode == Activity.RESULT_OK){ Bundle bundle = data.getExtras(); Toast.makeText(MainActivity.this, bundle.getString("result"), Toast.LENGTH_SHORT).show(); //result中保留了二维码的内容 } break; default: break; } }}
2.MipcaActivity.java(二维码处理类):
package com.example.scancodedemo;import java.io.IOException;import java.util.Vector;import android.app.Activity;import android.content.Intent;import android.content.res.AssetFileDescriptor;import android.graphics.Bitmap;import android.media.AudioManager;import android.media.MediaPlayer;import android.media.MediaPlayer.OnCompletionListener;import android.os.Bundle;import android.os.Handler;import android.os.Vibrator;import android.view.SurfaceHolder;import android.view.SurfaceHolder.Callback;import android.view.SurfaceView;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;import com.google.zxing.BarcodeFormat;import com.google.zxing.Result;import com.mining.app.zxing.camera.CameraManager;import com.mining.app.zxing.decoding.CaptureActivityHandler;import com.mining.app.zxing.decoding.InactivityTimer;import com.mining.app.zxing.view.ViewfinderView;/** * Initial the camera * @author Ryan.Tang */public class MipcaActivityCapture extends Activity implements Callback { private CaptureActivityHandler handler; private ViewfinderView viewfinderView; private boolean hasSurface; private Vector<BarcodeFormat> decodeFormats; private String characterSet; private InactivityTimer inactivityTimer; private MediaPlayer mediaPlayer; private boolean playBeep; private static final float BEEP_VOLUME = 0.10f; private boolean vibrate; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scan_code_activity); //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card); CameraManager.init(getApplication()); viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view); Button mButtonBack = (Button) findViewById(R.id.button_back); mButtonBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { MipcaActivityCapture.this.finish(); } }); hasSurface = false; inactivityTimer = new InactivityTimer(this); } @Override protected void onResume() { super.onResume(); SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view); SurfaceHolder surfaceHolder = surfaceView.getHolder(); if (hasSurface) { initCamera(surfaceHolder); } else { surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } decodeFormats = null; characterSet = null; playBeep = true; AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { playBeep = false; } initBeepSound(); vibrate = true; } @Override protected void onPause() { super.onPause(); if (handler != null) { handler.quitSynchronously(); handler = null; } CameraManager.get().closeDriver(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); super.onDestroy(); } /** * ????????? * @param result * @param barcode */ public void handleDecode(Result result, Bitmap barcode) { inactivityTimer.onActivity(); playBeepSoundAndVibrate(); String resultString = result.getText(); if (resultString.equals("")) { Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show(); }else { Intent resultIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("result", resultString); bundle.putParcelable("bitmap", barcode); resultIntent.putExtras(bundle); this.setResult(RESULT_OK, resultIntent); } MipcaActivityCapture.this.finish(); } private void initCamera(SurfaceHolder surfaceHolder) { try { CameraManager.get().openDriver(surfaceHolder); } catch (IOException ioe) { return; } catch (RuntimeException e) { return; } if (handler == null) { handler = new CaptureActivityHandler(this, decodeFormats, characterSet); } } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } @Override public void surfaceCreated(SurfaceHolder holder) { if (!hasSurface) { hasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { hasSurface = false; } public ViewfinderView getViewfinderView() { return viewfinderView; } public Handler getHandler() { return handler; } public void drawViewfinder() { viewfinderView.drawViewfinder(); } private void initBeepSound() { if (playBeep && mediaPlayer == null) { // The volume on STREAM_SYSTEM is not adjustable, and users found it // too loud, // so we now play on the music stream. setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = getResources().openRawResourceFd( R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException e) { mediaPlayer = null; } } } private static final long VIBRATE_DURATION = 200L; private void playBeepSoundAndVibrate() { if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } if (vibrate) { Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrator.vibrate(VIBRATE_DURATION); } } /** * When the beep has finished playing, rewind to queue up another one. */ private final OnCompletionListener beepListener = new OnCompletionListener() { public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.seekTo(0); } };}
3.CreateQRImage.java(字符串生成二维码工具类):
package com.example.scancodedemo;import java.util.Hashtable;import android.graphics.Bitmap;import android.widget.ImageView;import com.google.zxing.BarcodeFormat;import com.google.zxing.EncodeHintType;import com.google.zxing.WriterException;import com.google.zxing.common.BitMatrix;import com.google.zxing.qrcode.QRCodeWriter;public class CreateQRImage{ private Bitmap bitmap; private int QR_WIDTH = 200, QR_HEIGHT = 200; public Bitmap createQRImage(String url) { try { if (!(url == null || "".equals(url) || url.length() < 1)) { Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); BitMatrix bitMatrix = new QRCodeWriter().encode(url, 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; } } } 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 bitmap; }}
4.CodeShowActivity.java(二维码显示页):
package com.example.scancodedemo;import android.app.Activity;import android.graphics.Bitmap;import android.os.Bundle;import android.view.Window;import android.widget.ImageView;public class CodeShowActivity extends Activity { private ImageView mImgCodeShow; CreateQRImage createQRImageTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.code_show_activity); mImgCodeShow=(ImageView)findViewById(R.id.img_code_show); createQRImageTest=new CreateQRImage(); Bitmap bitmap=createQRImageTest.createQRImage("http://www.baidu.com"); mImgCodeShow.setImageBitmap(bitmap); }}
布局文件
1.scan_code_activity.xml:
<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <SurfaceView android:id="@+id/preview_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" /> <com.mining.app.zxing.view.ViewfinderView android:id="@+id/viewfinder_view" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <include android:id="@+id/include1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" layout="@layout/activity_title" /> </RelativeLayout></FrameLayout>
2.activity_main.xml很简单就不写了
3.code_show_activity.xml里面就一个ImageView,用于展示生成的二维码。
下面我们运行一下我们的demo:
扫描出的信息以Toast的形式打印出(baidu)
看的出,我们的demo可以正常运行。
我们关注的不是代码能不能懂,是能不能用,哈。按照我上面的截图复制到你的项目中,应该不会有太大的问题,这些步骤都是我亲自试过的。有问题可以联系我。
喜欢的朋友关注我吧,给我个支持!
源码下载
版权声明:本文为博主原创文章,未经博主允许不得转载。