安卓生成、显示二维码APP代码实现

你好!这里是风筝的博客,

欢迎和我一起交流。


开发工具:Android Studio。

需要一个jar包:http://download.csdn.net/detail/guet_kite/9885632

这是一个生成QR二维码的包。

至于怎么导包,Google下你就知道,不会Google都不好意思说自己是程序员。

 

先上第一道菜,UI界面的代码:

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tao.hotel.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="注销"
        android:id="@+id/delete"
        android:layout_marginRight="42dp"
        android:layout_marginEnd="42dp"
        android:layout_alignTop="@+id/key"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="二维码"
        android:id="@+id/key"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="69dp" />

    <ImageView android:id="@+id/img_qr"
        android:layout_gravity="center"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_below="@+id/delete"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="65dp" />

</RelativeLayout>


显示的UI界面应该是这样的:

 

 

主要就是两个Button和一个ImageView而已,没什么难的。

 

接下来第二道菜,主要代码:

 

package com.example.tao.hotel;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

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;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;

/**
 * Created by kite on 2017/4/17.
 */
public class HotelActivity extends Activity implements OnClickListener{

    ImageView imageView;
    Button button_key;

    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
		  case 0x22:
                    imageView.setVisibility(View.VISIBLE);
                    String fileName ="qr_" + System.currentTimeMillis() + ".jpg";/*文件名称=qr_系统时间.jpg*/
                    File file = getFileRoot(fileName);
                    Bitmap bitmap=createQRImage("Welcome!This is a QR_code", imageView,200,200);/*二维码信息:Welcome!This is a QR_code*/
                    saveImage(HotelActivity.this, bitmap, file, fileName);
                    //button_key.setEnabled(true);
                    break;
                case 0x23:
                    imageView.setVisibility(View.GONE);
                    button_key.setEnabled(true);
                    Toast.makeText(getApplicationContext(), "注销成功", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hotel);

        imageView = (ImageView) findViewById(R.id.img_qr);
        button_key = (Button) findViewById(R.id.key);
        button_key.setOnClickListener(this);
        Button button_delete = (Button) findViewById(R.id.delete);
        button_delete.setOnClickListener(this);

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.key:
                button_key.setEnabled(false);
                new Thread() {
                    boolean key_flag=true;
                    public void run() {       
                        handler.sendEmptyMessage(0x22);
                        Log.e("二维码", "success");
                    }
                }.start();
                break;

            case R.id.delete:
                new Thread() {
                    boolean key_flag=true;
                    String Del;
                    public void run() {
                        Log.e("删除成功:", "ok");
                        handler.sendEmptyMessage(0x23);
                    }
                }.start();
                break;
        }
    }
    //文件存储根目录
    private File getFileRoot(String fileName) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");/*文件保存在手机根目录:Boohee*/
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File file = new File(appDir, fileName);
            Log.e("路径:", file.toString());
            return file;
        }
        return null;
    }
    //要转换的地址或字符串,可以是中文
    public static Bitmap createQRImage(String url, ImageView sweepIV, int QR_WIDTH, int QR_HEIGHT ) {
        try {//判断URL合法性
            if (url == null || "".equals(url) || url.length() < 1) {
                return null;
            }
            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循环是图片横列扫描的结果
            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_HEIGHT + x] = 0xffffffff;
                    }
                }
            }//生成二维码图片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            //显示到一个ImageView上面
            sweepIV.setImageBitmap(bitmap);
            return bitmap;
            }
            catch (WriterException e) {
                e.printStackTrace();
            }
        return null;
    }
    //保存图片
    public static void saveImage(Context context,Bitmap bitmap,File filePath,String fileName){
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {// 把文件插入到系统图库
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    filePath.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://" + "/sdcard/Boohee/image.jpg")));
    }
}


主要就是利用之前导入的QR的jar包,来生成一个QR二维码,二维码不过是数据的载体而已,存储什么数据都无所谓。还有,这个二维码生成后我把它存到手机本地内存了,并且更新到图库中,这样,点开手机的相册即可看到生成的二维码,但是,在注销那里,偷了下懒,只是把ImageView隐藏了而已,本地的二维码图片并没有删除,嘿嘿,自己动手实现吧,懒得写了......

 

还有,记得在AndroidManifest.xml文件加上权限:

 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />//SD卡权限
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />//SD卡权限

 

 

 

好了,基本就这样,所有东西都放出来了,如果你还不会,那你来找我吧,咱俩抱头痛哭去吧,我也不怎么会......

 

 

 

 

 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值