Android QR码阅读器相机无法打开

时间:2018-10-19 18:54:43

标签: android

我面临的问题之一是,我使用Google Mobile Vision库构建了Android条码读取器,并且一旦授予了摄像头许可,我的应用程序就无法打开QR码读取器摄像头。清单中已经定义了摄像头权限,但是,在单击条形码读取器按钮时,摄像头仍然无法正常工作并关闭应用程序。有解决这个问题的解决方案吗?

这是构建gradle代码

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "com.example.johnn.lodgingservicesystemowner"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })


    implementation 'com.google.zxing:core:3.3.0'
    implementation 'com.google.android.gms:play-services-vision:11.0.2'
    implementation 'info.androidhive:barcode-reader:1.1.5'
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support:support-v4:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.github.bumptech.glide:glide:3.8.0'
    testImplementation 'junit:junit:4.12'
    implementation 'com.google.firebase:firebase-core:16.0.3'
    implementation 'com.google.firebase:firebase-messaging:17.3.2'
    implementation 'com.google.android.gms:play-services-maps:15.0.1'
    implementation 'com.google.android.gms:play-services-location:15.0.1'
}
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true

活动代码

public class ScanActivity extends AppCompatActivity implements BarcodeReader.BarcodeReaderListener {

private  BarcodeReader barcodeReader;
String lodgingId = "", userId="";

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

    transparentToolbar();
   // getSupportActionBar().hide();

    barcodeReader = (BarcodeReader) getSupportFragmentManager().findFragmentById(R.id.barcode_fragment);
}

private void transparentToolbar() {
    if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
        setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
    }
    if (Build.VERSION.SDK_INT >= 19) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }
    if (Build.VERSION.SDK_INT >= 21) {
        setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
    }
}

private void setWindowFlag(Activity activity, final int bits, boolean on) {
    Window win = activity.getWindow();
    WindowManager.LayoutParams winParams = win.getAttributes();
    if (on) {
        winParams.flags |= bits;
    } else {
        winParams.flags &= ~bits;
    }
    win.setAttributes(winParams);
}

private boolean isJSONValid(String s) {
    try {
        new JSONObject(s);
    } catch (JSONException ex) {
        try {
            new JSONArray(s);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}


@Override
public void onScanned(Barcode barcode) {
    // playing barcode reader beep sound
    barcodeReader.playBeep();

    //check whether it's a json

    if (isJSONValid(barcode.displayValue)) {
        try {
            JSONObject jsonBObj = new JSONObject(barcode.displayValue);

            lodgingId = jsonBObj.getString(LodgingData.KEY_LODGING_ID);
            userId = jsonBObj.getString(LodgingData.KEY_USER_ID);


            //display bulletin


            Intent intent = new Intent(ScanActivity.this, ViewLodgingDetails.class);
            intent.putExtra("LodgingID", lodgingId);
            intent.putExtra("UserID", userId);
            startActivity(intent);

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                barcodeReader.pauseScanning();
                new AlertDialog
                        .Builder(ScanActivity.this)
                        .setTitle(R.string.alert_error)
                        .setMessage("Bulletin Not Found, Please Try Again.")
                        .setPositiveButton(R.string.confirmation_ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                                barcodeReader.resumeScanning();
                            }
                        })
                        .setIcon(R.drawable.ic_error_outline_black_24dp)
                        .create()
                        .show();
            }
        });

    }
}

@Override
public void onScannedMultiple(List<Barcode> list) {
}

@Override
public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
}

@Override
public void onScanError(String errorMessage) {
}


@Override
public void onCameraPermissionDenied() {
    Toast.makeText(getApplicationContext(), "Camera permission denied!", Toast.LENGTH_LONG).show();

}

}

1 个答案:

答案 0 :(得分:0)

在Android 6.0及更高版本上,您还需要在runtime期间请求权限。

您可以先通过

检查您是否已获得许可
ContextCompat.checkSelfPermission(context,Manifest.permission.CAMERA);

如果返回假,则可以请求

ActivityCompat.requestPermissions(context,
                    new String[]{Manifest.permission.CAMERA},
                    requestCode);