因客戶上需要用到這個功能,就在網上找了一堆資料,全是說得不清不楚,Android用zxing,IOS用zbar,然后給出各種收費地址下載,這里我只用到掃碼功能,生成條形碼,二維碼功能一樣的道理,下面直接上教程。
鏈接:https://pan.baidu.com/s/1MJdIODuFzJQYTRMXflgyEg
提取碼:jv6n
下載好這個作為依賴,可以創建一個空項目,或者在原有的項目上跟着我走:File --> new --> import Module

選擇剛剛下載好的包目錄,確定。之后:File --> Project Structure(項目結構)

點擊 "+" 后選擇 "Module dependency" , 然后選擇我們import 的 module , 然后:apply -->確定

這樣就導入完成了。接下來就開始實現掃描功能;
直接上代碼:布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.tmri.enforcement.app.RequestAction" android:orientation="vertical" android:background="#87CEEB"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:orientation="horizontal"> <EditText android:id="@+id/edit_lsh" android:layout_width="0dp" android:layout_weight="3" android:layout_height="40dp" android:textSize="18sp" /> <Button android:id="@+id/btnSweep" android:layout_width="0dp" android:layout_height="40dp" android:layout_weight="1" android:text="掃描"/> </LinearLayout> </LinearLayout> </LinearLayout>
邏輯實現代碼:CaptureActivity是依賴中實現掃碼功能的一個類,直接調用就能實現掃碼,然后在onActivityResult()方法中拿到我們要的數據。
stringLSH = this.findViewById(R.id.edit_lsh); /*二維碼掃描*/ btnSweep = this.findViewById(R.id.btnSweep); btnSweep.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent sweep = new Intent(RequestAction.this, CaptureActivity.class); startActivityForResult(sweep,1003); } }); @Override public void onActivityResult(int requestCode , int resultCode , Intent data){ super.onActivityResult(requestCode , resultCode , data); if (resultCode == RESULT_OK){ String result = data.getExtras().getString("result"); stringLSH.setText(result); } }
/*申請手機權限,在oncreate()方法中調用*/
public void requestPermissions(){
String [] permissions = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.VIBRATE,
};
ActivityCompat.requestPermissions(RequestAction.this,permissions,100);
}
最后在運行項目之前記得在AndroidManifest.xml中添加權限:
<!--網絡權限-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--震動權限-->
<uses-permission android:name="android.permission.VIBRATE"/>
<!--攝像頭權限-->
<uses-permission android:name="android.permission.CAMERA"/>
<!--自動聚焦權限-->
<uses-feature android:name="android.hardware.camera.autofocus"/>
最后掃描直接將結果填入:

掃碼功能大功告成。
要做生成二維碼,直接調用zxing中的生成類就可以了。
