2012-07-27 24 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