藍牙基本的連接流程:
隨着可穿戴設備的流行,研究藍牙是必不可少的一門技術了。
藍牙權限
首先需要AndroidManifest.xml文件中添加操作藍牙的權限。
1 2 3 4 |
|
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 獲取藍牙適配器 Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); // 查找配對歷史 if(devices.size() == 0){ ToastUtil.showShort("請與打印機的藍牙匹配好!"); isBluetooth = false; //return; }else{ if (mBluetoothAdapter == null) { Toast.makeText(this, "您的設備不支持藍牙", 0).show(); return; } IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); mBtAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { Log.i("設備",device.getName() + "\n" + device.getAddress()); lanya=device.getName() + "\n" + device.getAddress(); } } mBtAdapter.cancelDiscovery(); String address=lanya.substring(lanya.length() - 17); if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); } if (mService==null) { mService = new BluetoothService(this, mHandler); } BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); mService.connect(device); }
private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_STATE_CHANGE: switch (msg.arg1) { case BluetoothService.STATE_CONNECTED: Log.i("開始",mConnectedDeviceName+"開開"); // Log.i("鏈接",mConnectedDeviceName+"123456789"); // print_connect_btn.append(mConnectedDeviceName); break; case BluetoothService.STATE_CONNECTING: Log.i("開始連接","正在連接..."); break; case BluetoothService.STATE_LISTEN: case BluetoothService.STATE_NONE: Log.i("ceroor","無連接"); break; } break; case MESSAGE_WRITE: //byte[] writeBuf = (byte[]) msg.obj; // construct a string from the buffer //String writeMessage = new String(writeBuf); break; case MESSAGE_READ: //byte[] readBuf = (byte[]) msg.obj; // construct a string from the valid bytes in the buffer //String readMessage = new String(readBuf, 0, msg.arg1); break; case MESSAGE_DEVICE_NAME: // save the connected device's name mConnectedDeviceName = msg.getData().getString(DEVICE_NAME); break; case MESSAGE_TOAST: ToastUtil.showShort("沒發現打印機設備,請退出!"); showLY(); break; } } }; private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) { String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); } }; private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @SuppressLint("MissingPermission") @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { //Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { //mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } //When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle("選擇連接的設備"); } } };
// 根據手機屏幕大小截屏生成圖片
public void viewSaveToImage(View view) { view.setDrawingCacheEnabled(true); view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); view.setDrawingCacheBackgroundColor(Color.WHITE); // 把一個View轉換成圖片 Bitmap cachebmp = loadBitmapFromView(view); // 添加水印 Bitmap bitmap = Bitmap.createBitmap(createWatermarkBitmap(cachebmp, "")); FileOutputStream fos; try { // 判斷手機設備是否有SD卡 boolean isHasSDCard = Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); if (isHasSDCard) { // SD卡根目錄 File sdRoot = Environment.getExternalStorageDirectory(); File file = new File(sdRoot, "gao.png"); fos = new FileOutputStream(file); } else throw new Exception("創建文件失敗!"); bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } view.destroyDrawingCache(); } private Bitmap loadBitmapFromView(View v) { int w = 500; int h = 385; Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bmp); c.drawColor(Color.WHITE); /** 如果不設置canvas畫布爲白色,則生成透明 */ v.layout(0, 0, w, h); v.draw(c); return bmp; } // 爲圖片target添加水印 private Bitmap createWatermarkBitmap(Bitmap target, String str) { int w = target.getWidth(); int h = target.getHeight(); Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bmp); Paint p = new Paint(); // 水印的顏色 p.setColor(Color.RED); // 水印的字體大小 p.setTextSize(16); p.setAntiAlias(true);// 去鋸齒 canvas.drawBitmap(target, 0, 0, p); // 在中間位置開始添加水印 canvas.drawText(str, w / 2, h / 2, p); canvas.save(Canvas.ALL_SAVE_FLAG); canvas.restore(); return bmp; }
// 把圖片轉成二進制發送給熱敏打印機
try{ RelativeLayout layout = new LoadAlert(PoWeighActivity.this,relative,"打印中..").getLoadAlert(); String path= Environment.getExternalStorageDirectory()+"/gao.png"; File mFile=new File(path); //若該文件存在 Bitmap bitmap = null; if (mFile.exists()) { bitmap= BitmapFactory.decodeFile(path); } sendMessage(bitmap,layout); }catch (Exception e){ ToastUtil.showShort("打印失敗!"); e.printStackTrace(); }