主页面
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but_zing = findViewById(R.id.but_zing);
but_zing.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
//扫描操作
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.initiateScan();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 100);
}
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "权限打开", Toast.LENGTH_SHORT).show();
} else {
finish();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
String result = scanResult.getContents();
Log.d("code", result);
//变量result就是二维码解码后的信息。
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}}
下载jar包
repositories {
mavenCentral()
maven {
url "http://dl.bintray.com/journeyapps/maven"
}
}
dependencies {
implementation fileTree(dir: ‘libs’, include: [’*.jar’])
implementation ‘com.android.support:appcompat-v7:26.1.0’
implementation ‘com.android.support.constraint:constraint-layout:1.1.3’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘com.android.support.test?1.0.2’
androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.2’
implementation 'com.journeyapps:zxing-android-embedded:2.0.1@aar'
implementation 'com.journeyapps:zxing-android-legacy:2.0.1@aar'
implementation 'com.journeyapps:zxing-android-integration:2.0.1@aar'
implementation 'com.google.zxing:core:3.0.1'
}
权限
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
布局
<Button
android:text="按钮"
android:id="@+id/but_zing"
android:layout_width="match_parent"
android:layout_height="wrap_content" />