android扫描二维码和生产二维码

时间:2022-11-17 07:30:09

极客学院扫描二维码和生成二维码

package com.example.testqr;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.WriterException;
import com.zxing.activity.CaptureActivity;
import com.zxing.encoding.EncodingHandler;

public class MainActivity extends Activity {
	
	private Button startScan;
	
	private Button generateQr;
	
	private ImageView qrImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startScan = (Button) findViewById(R.id.startScan);
        generateQr = (Button) findViewById(R.id.generateQRCODE);
        qrImageView = (ImageView)findViewById(R.id.qrIV);
        startScan.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(MainActivity.this,CaptureActivity.class);
				startActivityForResult(intent, 0);
			}
		});
        
        generateQr.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				try {
					Bitmap bitmap = EncodingHandler.createQRCode("dota", 400);
					qrImageView.setImageBitmap(bitmap);
				} catch (WriterException e) {
					e.printStackTrace();
				}
			}
		});
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(resultCode == RESULT_OK){
    		String str = data.getStringExtra("result");
    		Toast.makeText(MainActivity.this, str, 0).show();
    	}
    }
    
}

主要说明
1:用的库 是在极客学院 资料里的库 也是下的网上的 因为报错 把switch case 改成了 if else
2:扫描二维码是CaptureActivity
3:生成二维码的方法

   Bitmap bitmap = EncodingHandler.createQRCode("dota", 400);
   qrImageView.setImageBitmap(bitmap);