2012-07-27 50 views
0

我正在实施一种方法来解码QR码并返回包含在Android应用程序代码中的字符。 我想运行此方法,直到QR码解码成功并返回空值。在Android应用程序中使用循环解码QR码的方法

它在第一次循环运行正确。 但是,当它在第一个循环中读取失败时,它很少从第二个循环开始解码代码。 有时它也会陷入无限循环。

如果您有一些提示,请让我知道。

public String readQRCode(Bitmap file) { 
    Reader reader = new MultiFormatReader(); 
    Result result = null; 
    do { 
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(intent, REQUEST_IMAGE); 
     Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show(); 

     LuminanceSource source = new RGBLuminanceSource(file); 
     BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
       source)); 
     // Decode 
     try { 
      result = reader.decode(binaryBitmap); 
     } catch (NotFoundException e) { 
      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
      startActivityForResult(intent, REQUEST_IMAGE); 
      Toast.makeText(this, "Please try again", Toast.LENGTH_LONG).show(); 
      e.printStackTrace(); 
     } catch (ChecksumException e) { 
      e.printStackTrace(); 
     } catch (FormatException e) { 
      e.printStackTrace(); 
     } 
    } while (result == null || result.getText() == null); 

    return result.getText(); 
} 

回答

1

你已经创建了一个看起来很忙的等待循环。你需要完全重写逻辑。

startActivityForResult不会返回值,所以您不应该在调用活动时使用相同的方法处理结果。您应该在onActivityResult中进行处理。

参见文档就在这里: http://developer.android.com/reference/android/app/Activity.html#StartingActivities

你的情况:

  • 消除环路,不readQRCode
  • 做任何 “结果”
  • 添加一个onActivityResult方法,做startActivityForResult后面的所有内容
  • 如果要循环,请从startActivityForResult调用readQRCode

最终结果不应有任何形式的循环。

BTW:如果您希望我们更正代码,我们还需要查看当前startActivityForResult中的内容。

+0

非常感谢您的帮助!我删除了readQRCode方法,并在onActivityMethod中编写了与“result”(无循环)相关的代码。然后我终于可以解决问题了。 – Benben 2012-07-28 22:46:58