Android扫描和生成二维码

2020-11-04 15:25:29 浏览数 (1)

本文实例为大家分享了Android扫描和生成二维码的具体代码,供大家参考,具体内容如下

MainActivity.java

代码语言:javascript复制
public class MainActivity extends AppCompatActivity {

 private ImageView mImageView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button button =findViewById(R.id.btn);
  mImageView =findViewById(R.id.img);
  button.setOnClickListener(new View.OnClickListener() { //点击按钮扫描二维码
   @Override
   public void onClick(View view) {
    Intent intent = new Intent(MainActivity.this,CaptureActivity.class);


    startActivityForResult(intent,2);
   }
  });

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode==200&& resultCode==RESULT_OK){

   if (data!=null){
    String content = data.getStringExtra(Constant.CODED_CONTENT);
    if (TextUtils.isEmpty(content)){

     Toast.makeText(MainActivity.this, "您的输入为空!", Toast.LENGTH_SHORT).show();
     return;

    }

    Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    try {
     Bitmap bitmap = CodeCreator.createQRCode(content, 400, 400, logo);
     mImageView.setImageBitmap(bitmap);
    } catch (WriterException e) {
     e.printStackTrace();
    }

    Toast.makeText(MainActivity.this,"扫描" content,Toast.LENGTH_SHORT).show();


   }
  }
 }
}

activity.main.xml

代码语言:javascript复制
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity"
 android:orientation="vertical" 

 <Button
  android:id="@ id/btn"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="扫一扫"/ 

 <ImageView
  android:id="@ id/img"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  / 

</android.support.constraint.ConstraintLayout 

需要配置的权限

代码语言:javascript复制
<uses-permission android:name="android.permission.INTERNET"/ 
 <uses-permission android:name="android.permission.CAMERA" </uses-permission 
 <uses-permission android:name="android.permission.VIBRATE" / 
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" </uses-permission 
 <uses-feature android:name="android.hardware.camera" / 
 <uses-feature android:name="android.hardware.camera.autofocus" / 
 <uses-permission android:name="android.permission.FLASHLIGHT" / 

build.gradle

代码语言:javascript复制
minSdkVersion 16  //配置16
implementation'com.github.yuzhiqiang1993:zxing:2.2.1' //依赖

外部build.gradle

代码语言:javascript复制
allprojects {
 repositories {
  google()
  jcenter()
  maven { url 'https://jitpack.io' } //加这行代码
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助。

0 人点赞