Zxing via intent

2019-09-26 07:34发布

问题:

In my application I use the zxing library. I start de zxing barcodescanner via intent. But when the user has no barcodescanner installed. The application stops working. How can I check if a zxing barcodescanner is already installed?

回答1:

You can use following snippet to check if particular application is installed on user's device

try{
    ApplicationInfo info = getPackageManager().
            getApplicationInfo("com.facebook.android", 0 );
    return true;
} catch( PackageManager.NameNotFoundException e ){
    return false;
}

For Specific Zxing you will use following.

 Intent intent1 = new Intent("com.google.zxing.client.android.SCAN");
 List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent1,     
            PackageManager.MATCH_DEFAULT_ONLY);    
        if(list.size() > 0)  
                // Zxing is available 
        else  
           // Zxing is not available       

Once you find Zxing is available you can call it as follows

public Button.OnClickListener mScan = new Button.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
        startActivityForResult(intent, 0);
    }
};

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            // Handle successful scan
        } else if (resultCode == RESULT_CANCELED) {
            // Handle cancel
        }
    }
}


回答2:

There's a page on the zxing wiki that explicitly mentions this case:

How to scan a barcode from another Android application via Intents

The best way to integrate is to use the small library of code we have provided. It correctly handles for you many details, such as setting category, flags, picking the most appropriate app, and most importantly handling the case where Barcode Scanner is not installed.