这是扫描二维码的function。
public void scanQR(View v)
{
try
{
Intent intent = new Intent(ACTION_SCAN);
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
catch (ActivityNotFoundException anfe)
{
showDialog(ActivityUserDetails.this, "No Scanner Found",
"Download a scanner code activity?", "Yes", "No").show();
}
}
在上面的代码 sn-p 中,我从 catch 块中调用了 showDialog() 方法,这将显示一个 AlertDialog 要求从 Google Play 安装“条形码扫描仪”应用程序。下面给出了showDialog 方法的代码。
private static AlertDialog showDialog(final Activity act,
CharSequence title, CharSequence message, CharSequence buttonYes,
CharSequence buttonNo)
{
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(act);
downloadDialog.setTitle(title);
downloadDialog.setMessage(message);
downloadDialog.setPositiveButton(buttonYes,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
Uri uri = Uri.parse("market://search?q=pname:"
+ "com.google.zxing.client.android");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
try
{
act.startActivity(intent);
}
catch (ActivityNotFoundException anfe)
{
}
}
});
downloadDialog.setNegativeButton(buttonNo,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialogInterface, int i)
{
}
});
return downloadDialog.show();
}
我在Button点击事件中使用了这个功能。因此Button 的代码如下(xml 文件)。
<Button
android:id="@+id/button_wr_scan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/button_shadow"
android:onClick="scanQR"
android:paddingRight="4dp"
android:paddingTop="4dp"
android:text="ScanQR" />
注意:使用此功能的前提是您必须在您的设备中预先安装“条形码扫描仪”应用程序。
希望对您有所帮助。
谢谢:)