編輯:關於 Android 程式設計
本例使用的打印機為佳博打印機,它支持藍牙、WiFi、USB 三種連接方式,這裡採用的是藍牙連接。
起初在網上找到了佳博官方針對安卓開發的 App 源碼,但由於各種頁面跳轉較多,一時沒看太懂,於是又去搜尋資料,找到了一篇不錯的文章。
Android 從 2.0 版本的 SDK 才開始支持藍牙開發,而且模擬器不支持,測試至少需要兩部手機,這也在一定程度上制約了很多開發者。
1. 首先,要操作藍牙,需要在 AndroidManifest.xml 中加入相應權限:
// 管理藍牙設備的權限 <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /> // 使用藍牙設備的權限 <uses-permissionandroid:name="android.permission.BLUETOOTH" />
2. 打開藍牙
先獲得藍牙適配器(android.bluetooth.BluetoothAdapter),檢查設備是否支持藍牙,若支持則打開它。
// 檢查設備是否支持藍牙 adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { // 設備不支持藍牙 } // 打開藍牙 if (!adapter.isEnabled()) { Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 設置藍牙可見性,最多300秒 intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300); context.startActivity(intent); } 3. 獲取已配對的藍牙設備(android.bluetooth.BluetoothDevice)
首次連接某藍牙設備需要先配對,一旦配對成功,該設備的信息會被保存,之後連接時無需再次配對。不過要注意,已配對的設備不一定就能連接。
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> devices = adapter.getBondedDevices(); for(int i=0; i<devices.size(); i++) { BluetoothDevice device = (BluetoothDevice)devices.iterator().next(); System.out.println(device.getName()); } 4. 搜索周圍的藍牙設備
適配器搜索藍牙設備後會以廣播形式把結果發送出去,因此需要自定義一個繼承自廣播接收器的類,在 onReceive 方法中獲取並處理搜索結果。
// 設置廣播信息過濾 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // 注冊廣播接收器,接收並處理搜索結果 context.registerReceiver(receiver, intentFilter); // 尋找藍牙設備,android會將查找到的設備以廣播形式發出去 adapter.startDiscovery(); 自定義廣播類 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); } } } 5. 藍牙設備的配對與狀態監視
private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 獲取查找到的藍牙設備 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); System.out.println(device.getName()); // 如果查找到的設備符合要連接的設備,處理 if (device.getName().equalsIgnoreCase(name)) { // 搜索藍牙設備的過程占用資源比較多,一旦找到需要連接的設備後需要及時關閉搜索 adapter.cancelDiscovery(); // 獲取藍牙設備的連接狀態 connectState = device.getBondState(); switch (connectState) { // 未配對 case BluetoothDevice.BOND_NONE: // 配對 try { Method createBondMethod = BluetoothDevice.class.getMethod("createBond"); createBondMethod.invoke(device); } catch (Exception e) { e.printStackTrace(); } break; // 已配對 case BluetoothDevice.BOND_BONDED: try { // 連接 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { // 狀態改變的廣播 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getName().equalsIgnoreCase(name)) { connectState = device.getBondState(); switch (connectState) { case BluetoothDevice.BOND_NONE: break; case BluetoothDevice.BOND_BONDING: break; case BluetoothDevice.BOND_BONDED: try { // 連接 connect(device); } catch (IOException e) { e.printStackTrace(); } break; } } } } } 6. 藍牙設備的連接
private void connect(BluetoothDevice device) throws IOException { // 固定的UUID final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID uuid = UUID.fromString(SPP_UUID); BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid); socket.connect(); } 1. BluetoothAdapter,顧名思義就是藍牙適配器,在我們建立 bluetoothSocket 連接之前,都要不斷操作它。
BluetoothAdapter 的方法很多,常用的有以下幾個:
cancelDiscovery() 取消發現,也就是說當我們正在搜索設備時調用這個方法將停止搜索。
disable() 關閉藍牙。
enable() 打開藍牙,這個方法打開藍牙不會彈出提示。更多時候我們希望先詢問用戶是否打開,下面這兩行代碼同樣能打開藍牙,但會提示用戶:
Intent enabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enabler,reCode);//同startActivity(enabler);
getAddress() 獲取本地藍牙地址。
getDefaultAdapter() 獲取默認 BluetoothAdapter,實際上也只有這一種獲取方式。
getName() 獲取本地藍牙名稱。
getRemoteDevice(String address) 根據藍牙地址獲取遠程藍牙設備。
getState() 獲取本地藍牙適配器當前狀態(調試時尤為有用)。
isDiscovering() 判斷當前是否正在查找設備,是則返回 true。
isEnabled() 判斷藍牙是否打開,已打開返回 true,否則返回 false。
listenUsingRfcommWithServiceRecord(String name,UUID uuid) 根據名稱、UUID 創建並返回 BluetoothServerSocket,這是創建 BluetoothSocket 服務器端的第一步。
startDiscovery() 開始搜索,這是搜索的第一步。
2. BluetoothDevice,從名字就知道這個類描述了一個藍牙設備。
createRfcommSocketToServiceRecord(UUID uuid) 根據 UUID 創建並返回一個 BluetoothSocket。
這個方法也正是我們獲取 BluetoothDevice 的目的——創建 BluetoothSocket。
該類的其他方法,如 getAddress()、getName(),用法同 BluetoothAdapter。
3. BluetoothServerSocket,去掉 Bluetooth 想必大家就很熟悉了,既然是 Socket,方法應該大同小異。
這個類一共只有三個方法:
兩個重載的 accept()、accept(int timeout),區別在於後者可指定超時時間。需要注意的是,執行這兩個方法時,直到接收到客戶端請求(或超時)之前都會阻塞線程,因此應放在新線程中運行!
另外,這兩個方法都返回一個 BluetoothSocket,最終的連接就是服務器端與客戶端的兩個 BluetoothSocket 之間的連接。
close() 關閉,不必多說。
4. BluetoothSocket,與 BluetoothServerSocket 相對,代表客戶端。
一共 5 個方法,基本都會用到:
close() 關閉。
connect() 連接。
getInputStream() 獲取輸入流。
getOutputStream() 獲取輸出流。
getRemoteDevice() 獲取遠程設備,這裡指 bluetoothSocket 指定連接的那個遠程藍牙設備。
本例僅更改了最後的藍牙連接部分(因為佳博打印機有自己的 SDK,其中已封裝了連接方法)。將下載的 gprintersdkv22.jar 和 xUtils-2.6.14.jar 兩個包導入後,連接方法如下:
/** *連接 */ private void connect() { int rel =0; try{//使用端口1,4代表模式為藍牙模式,藍牙地址,最後默認為0 rel = mGpService.openPort(1,4,adressData.get(loction),0); }catch(RemoteException e) { e.printStackTrace(); } GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel]; if(r != GpCom.ERROR_CODE.SUCCESS) { if(r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) { //開啟成功 }else{ UIUtils.showMessage(GpCom.getErrorText(r)); } }else{ ProgressDialogUtil.dismiss(BuleToothActivity.this); UIUtils.showMessage("失敗"); } } 別忘了 mGpService 是佳博 SDK 自帶的一個服務,使用前要先獲取並與 Activity 進行綁定:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buletooth); connection(); } private void connection() { conn=newPrinterServiceConnection(); Intent intent =newIntent(this, GpPrintService.class); this.bindService(intent,conn, Context.BIND_AUTO_CREATE);// bindService } classPrinterServiceConnectionimplementsServiceConnection { @Override public void onServiceDisconnected(ComponentName name) { mGpService=null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mGpService= GpService.Stub.asInterface(service); } } 同時還要在清單文件中配置服務:
<service android:name="com.gprinter.service.GpPrintService" android:enabled="true" android:exported="true" android:label="GpPrintService"> <intent-filter> <actionandroid:name="com.gprinter.aidl.GpPrintService"/> </intent-filter> </service> <serviceandroid:name="com.gprinter.service.AllService"> </service>
做到這裡就大功告成,可以連上打印機了。不過此時還不能打印,需要進行一些打印配置。由於我的項目中連接與打印不在同一界面,於是繼續研究佳博源碼,發現只要前面連接已成功,在另一個界面只需一份配置就能直接打印。打印代碼如下:
public classPrintActivityextendsBaseActivityimplementsView.OnClickListener{ @Bind(R.id.print_print) Buttonprint; privateGpServicemGpService=null; privatePrinterServiceConnectionconn=null; private static final int MAIN_QUERY_PRINTER_STATUS=0xfe; private static final int REQUEST_PRINT_LABEL=0xfd; private static final int REQUEST_PRINT_RECEIPT=0xfc; private int mTotalCopies=0; @Override protected void initHandler() { handler=newHandler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); } }; } privateBroadcastReceivermBroadcastReceiver=newBroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d("TAG", action); // GpCom.ACTION_DEVICE_REAL_STATUS 為廣播的IntentFilter if(action.equals(GpCom.ACTION_DEVICE_REAL_STATUS)) { //業務邏輯的請求碼,對應哪裡查詢做什麼操作 intrequestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1); //判斷請求碼,是則進行業務操作 if(requestCode ==MAIN_QUERY_PRINTER_STATUS) { intstatus = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS,16); String str; if(status == GpCom.STATE_NO_ERR) { str ="打印機正常"; }else{ str ="打印機 "; if((byte) (status & GpCom.STATE_OFFLINE) > 0) { str +="脫機"; } if((byte) (status & GpCom.STATE_PAPER_ERR) > 0) { str +="缺紙"; } if((byte) (status & GpCom.STATE_COVER_OPEN) > 0) { str +="打印機開蓋"; } if((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) { str +="打印機出錯"; } if((byte) (status & GpCom.STATE_TIMES_OUT) > 0) { str +="查詢超時"; } } Toast.makeText(getApplicationContext(),"打印機:"+1+"狀態:"+ str, Toast.LENGTH_SHORT) .show(); }else if(requestCode ==REQUEST_PRINT_RECEIPT) { intstatus = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS,16); if(status == GpCom.STATE_NO_ERR) { sendReceipt(); }else{ Toast.makeText(PrintActivity.this,"query printer status error", Toast.LENGTH_SHORT).show(); } } } } }; @Override protected void initTitle() { mTitleTextMiddle.setText("打印"); } private void connection() { conn=newPrinterServiceConnection(); Intent intent =newIntent(this, GpPrintService.class); this.bindService(intent,conn, Context.BIND_AUTO_CREATE);// bindService } classPrinterServiceConnectionimplementsServiceConnection { @Override public void onServiceDisconnected(ComponentName name) { Log.i("ServiceConnection","onServiceDisconnected() called"); mGpService=null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mGpService= GpService.Stub.asInterface(service); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_print); connection(); //注冊實時狀態查詢廣播 registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_DEVICE_REAL_STATUS)); /** *票據模式下,可注冊該廣播,在需要打印內容的最後加入addQueryPrinterStatus(),在打印完成後會接收到 * action為GpCom.ACTION_DEVICE_STATUS的廣播,特別用於連續打印, *可參照該sample中的sendReceiptWithResponse方法與廣播中的處理 **/ registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_RECEIPT_RESPONSE)); /** *標簽模式下,可注冊該廣播,在需要打印內容的最後加入addQueryPrinterStatus(RESPONSE_MODE mode) *,在打印完成後會接收到,action為GpCom.ACTION_LABEL_RESPONSE的廣播,特別用於連續打印, *可參照該sample中的sendLabelWithResponse方法與廣播中的處理 **/ registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_LABEL_RESPONSE)); } @Override protected void initView() { print.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()) { caseR.id.print_print: if(mGpService==null) { UIUtils.showMessage("服務正在開啟"); }else{ try{ inttype =mGpService.getPrinterCommandType(1); if(type == GpCom.ESC_COMMAND) { mGpService.queryPrinterStatus(1,1000,REQUEST_PRINT_RECEIPT); }else{ Toast.makeText(this,"Printer is not receipt mode", Toast.LENGTH_SHORT).show(); } }catch(RemoteException e1) { e1.printStackTrace(); } } break; } } private void sendReceipt() { EscCommand esc =newEscCommand(); esc.addInitializePrinter(); esc.addPrintAndFeedLines((byte)3); esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//設置打印居中 esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);//設置為倍高倍寬 esc.addText("asdfkldsjgfsdl\n");//打印文字 esc.addPrintAndLineFeed(); /*打印文字 */ esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍寬 esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//設置打印左對齊 esc.addText("dfkdsgklfds\n");//打印文字 // esc.addText("Welcome to use SMARNET printer!\n"); //打印文字 // /*打印繁體中文需要打印機支持繁體字庫 */ // String message = "佳博智匯票據打印機\n"; // // esc.addText(message,"BIG5"); // esc.addText(message, "GB2312"); esc.addPrintAndLineFeed(); /*絕對位置具體詳細信息請查看GP58編程手冊 */ esc.addText("商品名稱"); esc.addSetHorAndVerMotionUnits((byte)7, (byte)0); esc.addSetAbsolutePrintPosition((short)6); esc.addText("訂單號"); esc.addSetAbsolutePrintPosition((short)10); esc.addText("狀態"); esc.addPrintAndLineFeed(); esc.addText("蘋果"); esc.addSetHorAndVerMotionUnits((byte)7, (byte)0); esc.addSetAbsolutePrintPosition((short)6); esc.addText("12345"); esc.addSetAbsolutePrintPosition((short)10); esc.addText("正常"); esc.addPrintAndLineFeed(); esc.addText("果粒橙300ml"); esc.addSetHorAndVerMotionUnits((byte)7, (byte)0); esc.addSetAbsolutePrintPosition((short)6); esc.addText("3545456"); esc.addSetAbsolutePrintPosition((short)10); esc.addText("正常"); esc.addPrintAndLineFeed(); // /*打印圖片 */ // esc.addText("Print bitmap!\n"); //打印文字 // Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.gprinter); // esc.addRastBitImage(b, 384, 0); //打印圖片 // /*打印一維條碼 */ // esc.addText("Print code128\n"); //打印文字 // esc.addSelectPrintingPositionForHRICharacters(EscCommand.HRI_POSITION.BELOW);// // //設置條碼可識別字符位置在條碼下方 // esc.addSetBarcodeHeight((byte) 60); //設置條碼高度為60點 // esc.addSetBarcodeWidth((byte) 1); //設置條碼單元寬度為1 // esc.addCODE128(esc.genCodeB("SMARNET")); //打印Code128碼 // esc.addPrintAndLineFeed(); /* * QRCode命令打印此命令只在支持QRCode命令打印的機型才能使用。在不支持二維碼指令打印的機型上,則需要發送二維條碼圖片 */ esc.addText("商家二維碼\n");//打印文字 esc.addSelectErrorCorrectionLevelForQRCode((byte)0x31);//設置糾錯等級 esc.addSelectSizeOfModuleForQRCode((byte)6);//設置qrcode模塊大小 esc.addStoreQRCodeData("dfgdgs");//設置qrcode內容 esc.addPrintQRCode();//打印QRCode esc.addPrintAndLineFeed(); /*打印文字 */esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//設置打印左對齊 esc.addText("Completed!\r\n");//打印結束 //開錢箱 esc.addGeneratePlus(LabelCommand.FOOT.F5, (byte)255, (byte)255); esc.addPrintAndFeedLines((byte)8); Vector<Byte> datas = esc.getCommand();//發送數據 byte[] bytes = GpUtils.ByteTo_byte(datas); String sss = Base64.encodeToString(bytes, Base64.DEFAULT); intrs; try{ rs =mGpService.sendEscCommand(1, sss); GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rs]; if(r != GpCom.ERROR_CODE.SUCCESS) { Toast.makeText(getApplicationContext(), GpCom.getErrorText(r), Toast.LENGTH_SHORT).show(); } }catch(RemoteException e) { //TODO Auto-generated catch block e.printStackTrace(); } } } 至此大功告成,當東西真正打印出來的時候,成就感十足。
以上就是本文關於 Android 手機通過藍牙連接佳博打印機的實例分享,涵蓋權限配置、藍牙搜索配對、SDK 綁定與指令打印等完整流程,希望對你有所幫助。如有疑問,歡迎留言交流。
用 Android Animation 做一個 loading 動畫
Animation 的用法門檻不高,這裡用一個 loading 效果把四種動畫都串一遍。 先看效果: Android 的 Animation 體系提供四種基本動畫: A
Android 圖片水平重複平鋪(repeat x)的兩種做法
做法一:用 Bitmap 的 tileMode 屬性 先建立 wave_repeat.xml: <?xml version=1.0 encoding=utf-8?
QQ厘米秀「挑戰厘米神搶手」怎麼玩?入口、規則與獎品說明
厘米秀是手機QQ把PC年代的QQ秀搬到手機上的嘗試:一個會動、會換裝、還會在對話框裡做動作的虛擬分身。除了聊天時多一個角色站在訊息旁邊,官方也不定期推出小遊戲,其中「挑戰
Android 基礎系列(八):自建並呼叫自訂的 ContentProvider
前面兩篇我們分別示範了如何讀寫聯絡人與短訊息,相信大家都已經熟悉 ContentProvider 的基本操作方式。但在實際專案中,除了消費系統或其他應用提供的資料,我們常