我想使用ZXingScannerView
, 通过我的应用读取 QR 码。我需要授予相机使用权限ZXingScannerView
,对吗?由于某种我不知道的原因,该视图不起作用。
无论如何,我是这么想的,所以我尝试授予权限,但它一直失败,说“包安装程序已停止”。我认为该错误是在线发生的
if(permissioncheck == PackageManager.PERMISSION_GRANTED)
这是完整的代码
ZXingScannerView mScanview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int permissioncheck = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if(permissioncheck == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "not ok", Toast.LENGTH_SHORT).show();
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
Toast.makeText(this, "ok?", Toast.LENGTH_SHORT).show();
}
else {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 1);
}
}
Button button = (Button)findViewById(R.id.qr_button);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
mScanview = new ZXingScannerView(getApplicationContext());
setContentView(mScanview);
}
});
}
@Override
public void onRequestPermissionsResult(int reqCode, String permissions[], int[] grantResult){
switch (reqCode){
case 1: {
if(grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "not ok", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
@Override
public void handleResult(Result result){
Log.v("TAG", result.getText());
Log.v("TAG", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
AlertDialog dialog = builder.create();
dialog.show();
}
@Override
public void onPause() {
super.onPause();
mScanview.stopCamera();
}
或者,如果您知道在应用程序中实现 QR 码阅读器的更好方法,您能告诉我吗?