最近在做一个安卓应用,其中有一个需求是要求用蓝牙连接打印机实现打印功能。一开始没有一点头绪,网上找了很多资料也找不到有用的数据。所以自己就去研究,最终,功夫不负有心人,顺利的完成了这个功能。下边贴出我写的代码,共有需要的IT哥们参考学习。

完整源码下载

我们先看看运行效果图吧。。。

1.这是主界面的效果图

贴上布局文件的代码:bluetooth_layout.xml

[html]  view plain copy
  1. <span style="font-size:12px"><?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <Button
  6. android:id="@+id/openBluetooth_tb"
  7. android:layout_width="130dp"
  8. android:layout_height="wrap_content"
  9. android:layout_alignParentRight="true"
  10. android:layout_marginRight="18dp"
  11. android:layout_marginTop="5dp"
  12. android:text="打开蓝牙" />
  13. <Button
  14. android:id="@+id/searchDevices"
  15. android:layout_width="match_parent"
  16. android:layout_height="wrap_content"
  17. android:layout_alignParentLeft="true"
  18. android:layout_below="@+id/openBluetooth_tb"
  19. android:layout_marginTop="20dp"
  20. android:text="搜索设备" />
  21. <View
  22. android:layout_width="match_parent"
  23. android:layout_height="3dp"
  24. android:layout_alignParentLeft="true"
  25. android:layout_below="@+id/searchDevices"
  26. android:background="@android:color/darker_gray" />
  27. <LinearLayout
  28. android:id="@+id/linearLayout1"
  29. android:layout_width="match_parent"
  30. android:layout_height="150dp"
  31. android:layout_marginTop="125dp"
  32. android:orientation="vertical" >
  33. <TextView
  34. android:layout_width="match_parent"
  35. android:layout_height="wrap_content"
  36. android:text="未配对设备" />
  37. <ListView
  38. android:id="@+id/unbondDevices"
  39. android:layout_width="wrap_content"
  40. android:layout_height="wrap_content" />
  41. </LinearLayout>
  42. <View
  43. android:layout_width="match_parent"
  44. android:layout_height="3dp"
  45. android:layout_alignParentLeft="true"
  46. android:layout_below="@+id/searchDevices"
  47. android:layout_marginTop="160dp"
  48. android:background="@android:color/darker_gray" />
  49. <LinearLayout
  50. android:layout_width="match_parent"
  51. android:layout_height="190dp"
  52. android:layout_marginTop="288dp"
  53. android:orientation="vertical" >
  54. <TextView
  55. android:layout_width="match_parent"
  56. android:layout_height="wrap_content"
  57. android:text="已配对设备" />
  58. <ListView
  59. android:id="@+id/bondDevices"
  60. android:layout_width="wrap_content"
  61. android:layout_height="wrap_content"
  62. android:layout_alignParentLeft="true"
  63. android:layout_below="@+id/linearLayout1" >
  64. </ListView>
  65. </LinearLayout>
  66. <Button
  67. android:id="@+id/return_Bluetooth_btn"
  68. android:layout_width="100dp"
  69. android:layout_height="wrap_content"
  70. android:layout_above="@+id/searchDevices"
  71. android:layout_alignParentLeft="true"
  72. android:text="返回" />
  73. </RelativeLayout></span>

从上边的布局文件中不难看出,其中有两个ListView,OK,那下边贴出对应的两个item布局文件

--> 第一个item:unbonddevice_item.xml

[html]  view plain copy
  1. <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <TextView
  6. android:id="@+id/device_name"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:layout_alignParentLeft="true"
  10. android:layout_alignParentTop="true"
  11. android:text="未绑定设备"
  12. android:textAppearance="?android:attr/textAppearanceLarge" />
  13. </RelativeLayout></span>

-->第二个item:bonddevice_item.xml

[html]  view plain copy
  1. <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <TextView
  6. android:id="@+id/device_name"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:layout_alignParentLeft="true"
  10. android:layout_alignParentTop="true"
  11. android:text="已绑定设备"
  12. android:textAppearance="?android:attr/textAppearanceLarge" />
  13. </RelativeLayout></span>

2.还有另外一个布局文件,就是当点击已绑定蓝牙设备下边的某个item时进入打印的界面,不多说,看图!

代码如下:printdata_layout.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <EditText
  6. android:id="@+id/print_data"
  7. android:layout_width="match_parent"
  8. android:layout_height="200dp"
  9. android:layout_alignParentLeft="true"
  10. android:layout_alignParentTop="true"
  11. android:layout_marginTop="46dp" >
  12. </EditText>
  13. <TextView
  14. android:id="@+id/device_name"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_alignParentLeft="true"
  18. android:layout_alignParentTop="true"
  19. android:layout_marginTop="16dp"
  20. android:text="Large Text"
  21. android:textAppearance="?android:attr/textAppearanceLarge" />
  22. <TextView
  23. android:id="@+id/connect_state"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:layout_alignBaseline="@+id/device_name"
  27. android:layout_alignBottom="@+id/device_name"
  28. android:layout_marginLeft="42dp"
  29. android:layout_toRightOf="@+id/device_name"
  30. android:text="Large Text"
  31. android:textAppearance="?android:attr/textAppearanceLarge" />
  32. <Button
  33. android:id="@+id/send"
  34. android:layout_width="match_parent"
  35. android:layout_height="wrap_content"
  36. android:layout_alignParentLeft="true"
  37. android:layout_below="@+id/print_data"
  38. android:layout_marginTop="21dp"
  39. android:text="打印" />
  40. <Button
  41. android:id="@+id/command"
  42. android:layout_width="match_parent"
  43. android:layout_height="wrap_content"
  44. android:layout_alignParentLeft="true"
  45. android:layout_below="@+id/send"
  46. android:text="指令" />
  47. </RelativeLayout>

至此,布局文件就搞定了,接下来就要编写java代码了。主要有一下这么几个类,一个一个来哈

BluetoothActivity.java

这个类的主要作用是初始化主界面,看代码

[java]  view plain copy
  1. public class BluetoothActivity extends Activity {
  2. private Context context = null;
  3. public void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. this.context = this;
  6. setTitle("蓝牙打印");
  7. setContentView(R.layout.bluetooth_layout);
  8. this.initListener();
  9. }
  10. private void initListener() {
  11. ListView unbondDevices = (ListView) this
  12. .findViewById(R.id.unbondDevices);
  13. ListView bondDevices = (ListView) this.findViewById(R.id.bondDevices);
  14. Button switchBT = (Button) this.findViewById(R.id.openBluetooth_tb);
  15. Button searchDevices = (Button) this.findViewById(R.id.searchDevices);
  16. BluetoothAction bluetoothAction = new BluetoothAction(this.context,
  17. unbondDevices, bondDevices, switchBT, searchDevices,
  18. BluetoothActivity.this);
  19. Button returnButton = (Button) this
  20. .findViewById(R.id.return_Bluetooth_btn);
  21. bluetoothAction.setSearchDevices(searchDevices);
  22. bluetoothAction.initView();
  23. switchBT.setOnClickListener(bluetoothAction);
  24. searchDevices.setOnClickListener(bluetoothAction);
  25. returnButton.setOnClickListener(bluetoothAction);
  26. }
  27. //屏蔽返回键的代码:
  28. public boolean onKeyDown(int keyCode,KeyEvent event)
  29. {
  30. switch(keyCode)
  31. {
  32. case KeyEvent.KEYCODE_BACK:return true;
  33. }
  34. return super.onKeyDown(keyCode, event);
  35. }
  36. }

BluetoothAction.java

这个类顾名思义,是处理bluetoothActivity中各种操作事件的action类,看代码

[java]  view plain copy
  1. <span style="font-size:14px">public class BluetoothAction implements OnClickListener {
  2. private Button switchBT = null;
  3. private Button searchDevices = null;
  4. private Activity activity = null;
  5. private ListView unbondDevices = null;
  6. private ListView bondDevices = null;
  7. private Context context = null;
  8. private BluetoothService bluetoothService = null;
  9. public BluetoothAction(Context context, ListView unbondDevices,
  10. ListView bondDevices, Button switchBT, Button searchDevices,
  11. Activity activity) {
  12. super();
  13. this.context = context;
  14. this.unbondDevices = unbondDevices;
  15. this.bondDevices = bondDevices;
  16. this.switchBT = switchBT;
  17. this.searchDevices = searchDevices;
  18. this.activity = activity;
  19. this.bluetoothService = new BluetoothService(this.context,
  20. this.unbondDevices, this.bondDevices, this.switchBT,
  21. this.searchDevices);
  22. }
  23. public void setSwitchBT(Button switchBT) {
  24. this.switchBT = switchBT;
  25. }
  26. public void setSearchDevices(Button searchDevices) {
  27. this.searchDevices = searchDevices;
  28. }
  29. public void setUnbondDevices(ListView unbondDevices) {
  30. this.unbondDevices = unbondDevices;
  31. }
  32. /**
  33. * 初始化界面
  34. */
  35. public void initView() {
  36. if (this.bluetoothService.isOpen()) {
  37. System.out.println("蓝牙有开!");
  38. switchBT.setText("关闭蓝牙");
  39. }
  40. if (!this.bluetoothService.isOpen()) {
  41. System.out.println("蓝牙没开!");
  42. this.searchDevices.setEnabled(false);
  43. }
  44. }
  45. private void searchDevices() {
  46. bluetoothService.searchDevices();
  47. }
  48. /**
  49. * 各种按钮的监听
  50. */
  51. @Override
  52. public void onClick(View v) {
  53. if (v.getId() == R.id.searchDevices) {
  54. this.searchDevices();
  55. } else if (v.getId() == R.id.return_Bluetooth_btn) {
  56. activity.finish();
  57. } else if (v.getId() == R.id.openBluetooth_tb) {
  58. if (!this.bluetoothService.isOpen()) {
  59. // 蓝牙关闭的情况
  60. System.out.println("蓝牙关闭的情况");
  61. this.bluetoothService.openBluetooth(activity);
  62. } else {
  63. // 蓝牙打开的情况
  64. System.out.println("蓝牙打开的情况");
  65. this.bluetoothService.closeBluetooth();
  66. }
  67. }
  68. }
  69. }</span>

这个类会把各种请求动作分门别类,交给BluetoothService.java来处理,看代码

[java]  view plain copy
  1. public class BluetoothService {
  2. private Context context = null;
  3. private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
  4. .getDefaultAdapter();
  5. private ArrayList<BluetoothDevice> unbondDevices = null; // 用于存放未配对蓝牙设备
  6. private ArrayList<BluetoothDevice> bondDevices = null;// 用于存放已配对蓝牙设备
  7. private Button switchBT = null;
  8. private Button searchDevices = null;
  9. private ListView unbondDevicesListView = null;
  10. private ListView bondDevicesListView = null;
  11. /**
  12. * 添加已绑定蓝牙设备到ListView
  13. */
  14. private void addBondDevicesToListView() {
  15. ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
  16. int count = this.bondDevices.size();
  17. System.out.println("已绑定设备数量:" + count);
  18. for (int i = 0; i < count; i++) {
  19. HashMap<String, Object> map = new HashMap<String, Object>();
  20. map.put("deviceName", this.bondDevices.get(i).getName());
  21. data.add(map);// 把item项的数据加到data中
  22. }
  23. String[] from = { "deviceName" };
  24. int[] to = { R.id.device_name };
  25. SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,
  26. R.layout.bonddevice_item, from, to);
  27. // 把适配器装载到listView中
  28. this.bondDevicesListView.setAdapter(simpleAdapter);
  29. this.bondDevicesListView
  30. .setOnItemClickListener(new OnItemClickListener() {
  31. @Override
  32. public void onItemClick(AdapterView<?> arg0, View arg1,
  33. int arg2, long arg3) {
  34. BluetoothDevice device = bondDevices.get(arg2);
  35. Intent intent = new Intent();
  36. intent.setClassName(context,
  37. "com.lifeng.jdxt.view.PrintDataActivity");
  38. intent.putExtra("deviceAddress", device.getAddress());
  39. context.startActivity(intent);
  40. }
  41. });
  42. }
  43. /**
  44. * 添加未绑定蓝牙设备到ListView
  45. */
  46. private void addUnbondDevicesToListView() {
  47. ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
  48. int count = this.unbondDevices.size();
  49. System.out.println("未绑定设备数量:" + count);
  50. for (int i = 0; i < count; i++) {
  51. HashMap<String, Object> map = new HashMap<String, Object>();
  52. map.put("deviceName", this.unbondDevices.get(i).getName());
  53. data.add(map);// 把item项的数据加到data中
  54. }
  55. String[] from = { "deviceName" };
  56. int[] to = { R.id.device_name };
  57. SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,
  58. R.layout.unbonddevice_item, from, to);
  59. // 把适配器装载到listView中
  60. this.unbondDevicesListView.setAdapter(simpleAdapter);
  61. // 为每个item绑定监听,用于设备间的配对
  62. this.unbondDevicesListView
  63. .setOnItemClickListener(new OnItemClickListener() {
  64. @Override
  65. public void onItemClick(AdapterView<?> arg0, View arg1,
  66. int arg2, long arg3) {
  67. try {
  68. Method createBondMethod = BluetoothDevice.class
  69. .getMethod("createBond");
  70. createBondMethod
  71. .invoke(unbondDevices.get(arg2));
  72. // 将绑定好的设备添加的已绑定list集合
  73. bondDevices.add(unbondDevices.get(arg2));
  74. // 将绑定好的设备从未绑定list集合中移除
  75. unbondDevices.remove(arg2);
  76. addBondDevicesToListView();
  77. addUnbondDevicesToListView();
  78. } catch (Exception e) {
  79. Toast.makeText(context, "配对失败!", Toast.LENGTH_SHORT)
  80. .show();
  81. }
  82. }
  83. });
  84. }
  85. public BluetoothService(Context context, ListView unbondDevicesListView,
  86. ListView bondDevicesListView, Button switchBT, Button searchDevices) {
  87. this.context = context;
  88. this.unbondDevicesListView = unbondDevicesListView;
  89. this.bondDevicesListView = bondDevicesListView;
  90. // this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  91. this.unbondDevices = new ArrayList<BluetoothDevice>();
  92. this.bondDevices = new ArrayList<BluetoothDevice>();
  93. this.switchBT = switchBT;
  94. this.searchDevices = searchDevices;
  95. this.initIntentFilter();
  96. }
  97. private void initIntentFilter() {
  98. // 设置广播信息过滤
  99. IntentFilter intentFilter = new IntentFilter();
  100. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  101. intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
  102. intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  103. intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  104. // 注册广播接收器,接收并处理搜索结果
  105. context.registerReceiver(receiver, intentFilter);
  106. }
  107. /**
  108. * 打开蓝牙
  109. */
  110. public void openBluetooth(Activity activity) {
  111. Intent enableBtIntent = new Intent(
  112. BluetoothAdapter.ACTION_REQUEST_ENABLE);
  113. activity.startActivityForResult(enableBtIntent, 1);
  114. }
  115. /**
  116. * 关闭蓝牙
  117. */
  118. public void closeBluetooth() {
  119. this.bluetoothAdapter.disable();
  120. }
  121. /**
  122. * 判断蓝牙是否打开
  123. *
  124. * @return boolean
  125. */
  126. public boolean isOpen() {
  127. return this.bluetoothAdapter.isEnabled();
  128. }
  129. /**
  130. * 搜索蓝牙设备
  131. */
  132. public void searchDevices() {
  133. this.bondDevices.clear();
  134. this.unbondDevices.clear();
  135. // 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
  136. this.bluetoothAdapter.startDiscovery();
  137. }
  138. /**
  139. * 添加未绑定蓝牙设备到list集合
  140. *
  141. * @param device
  142. */
  143. public void addUnbondDevices(BluetoothDevice device) {
  144. System.out.println("未绑定设备名称:" + device.getName());
  145. if (!this.unbondDevices.contains(device)) {
  146. this.unbondDevices.add(device);
  147. }
  148. }
  149. /**
  150. * 添加已绑定蓝牙设备到list集合
  151. *
  152. * @param device
  153. */
  154. public void addBandDevices(BluetoothDevice device) {
  155. System.out.println("已绑定设备名称:" + device.getName());
  156. if (!this.bondDevices.contains(device)) {
  157. this.bondDevices.add(device);
  158. }
  159. }
  160. /**
  161. * 蓝牙广播接收器
  162. */
  163. private BroadcastReceiver receiver = new BroadcastReceiver() {
  164. ProgressDialog progressDialog = null;
  165. @Override
  166. public void onReceive(Context context, Intent intent) {
  167. String action = intent.getAction();
  168. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  169. BluetoothDevice device = intent
  170. .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  171. if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
  172. addBandDevices(device);
  173. } else {
  174. addUnbondDevices(device);
  175. }
  176. } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
  177. progressDialog = ProgressDialog.show(context, "请稍等...",
  178. "搜索蓝牙设备中...", true);
  179. } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
  180. .equals(action)) {
  181. System.out.println("设备搜索完毕");
  182. progressDialog.dismiss();
  183. addUnbondDevicesToListView();
  184. addBondDevicesToListView();
  185. // bluetoothAdapter.cancelDiscovery();
  186. }
  187. if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
  188. if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
  189. System.out.println("--------打开蓝牙-----------");
  190. switchBT.setText("关闭蓝牙");
  191. searchDevices.setEnabled(true);
  192. bondDevicesListView.setEnabled(true);
  193. unbondDevicesListView.setEnabled(true);
  194. } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
  195. System.out.println("--------关闭蓝牙-----------");
  196. switchBT.setText("打开蓝牙");
  197. searchDevices.setEnabled(false);
  198. bondDevicesListView.setEnabled(false);
  199. unbondDevicesListView.setEnabled(false);
  200. }
  201. }
  202. }
  203. };
  204. }

到这里,第一个界面的代码就写完了,当我们点击要打印的蓝牙设备时就会跳转到打印页面,跳转代码在BluetoothService.java的addBondDevicesToListView()中

接下来让我们来看看第二个界面的代码,结构和第一个界面的代码一样,分类三个类,请看代码。。。。。

PrintDataActivity.java

[java]  view plain copy
  1. public class PrintDataActivity extends Activity {
  2. private Context context = null;
  3. public void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. this.setTitle("蓝牙打印");
  6. this.setContentView(R.layout.printdata_layout);
  7. this.context = this;
  8. this.initListener();
  9. }
  10. /**
  11. * 获得从上一个Activity传来的蓝牙地址
  12. * @return String
  13. */
  14. private String getDeviceAddress() {
  15. // 直接通过Context类的getIntent()即可获取Intent
  16. Intent intent = this.getIntent();
  17. // 判断
  18. if (intent != null) {
  19. return intent.getStringExtra("deviceAddress");
  20. } else {
  21. return null;
  22. }
  23. }
  24. private void initListener() {
  25. TextView deviceName = (TextView) this.findViewById(R.id.device_name);
  26. TextView connectState = (TextView) this
  27. .findViewById(R.id.connect_state);
  28. PrintDataAction printDataAction = new PrintDataAction(this.context,
  29. this.getDeviceAddress(), deviceName, connectState);
  30. EditText printData = (EditText) this.findViewById(R.id.print_data);
  31. Button send = (Button) this.findViewById(R.id.send);
  32. Button command = (Button) this.findViewById(R.id.command);
  33. printDataAction.setPrintData(printData);
  34. send.setOnClickListener(printDataAction);
  35. command.setOnClickListener(printDataAction);
  36. }
  37. @Override
  38. protected void onDestroy() {
  39. PrintDataService.disconnect();
  40. super.onDestroy();
  41. }
  42. }

PrintDataAction.java

[java]  view plain copy
  1. <span style="font-size:14px">public class PrintDataAction implements OnClickListener {
  2. private Context context = null;
  3. private TextView deviceName = null;
  4. private TextView connectState = null;
  5. private EditText printData = null;
  6. private String deviceAddress = null;
  7. private PrintDataService printDataService = null;
  8. public PrintDataAction(Context context, String deviceAddress,
  9. TextView deviceName, TextView connectState) {
  10. super();
  11. this.context = context;
  12. this.deviceAddress = deviceAddress;
  13. this.deviceName = deviceName;
  14. this.connectState = connectState;
  15. this.printDataService = new PrintDataService(this.context,
  16. this.deviceAddress);
  17. this.initView();
  18. }
  19. private void initView() {
  20. // 设置当前设备名称
  21. this.deviceName.setText(this.printDataService.getDeviceName());
  22. // 一上来就先连接蓝牙设备
  23. boolean flag = this.printDataService.connect();
  24. if (flag == false) {
  25. // 连接失败
  26. this.connectState.setText("连接失败!");
  27. } else {
  28. // 连接成功
  29. this.connectState.setText("连接成功!");
  30. }
  31. }
  32. public void setPrintData(EditText printData) {
  33. this.printData = printData;
  34. }
  35. @Override
  36. public void onClick(View v) {
  37. if (v.getId() == R.id.send) {
  38. String sendData = this.printData.getText().toString();
  39. this.printDataService.send(sendData + "\n");
  40. } else if (v.getId() == R.id.command) {
  41. this.printDataService.selectCommand();
  42. }
  43. }
  44. }</span>

PrintDataService.java

[java]  view plain copy
  1. <span style="font-size:14px">public class PrintDataService {
  2. private Context context = null;
  3. private String deviceAddress = null;
  4. private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
  5. .getDefaultAdapter();
  6. private BluetoothDevice device = null;
  7. private static BluetoothSocket bluetoothSocket = null;
  8. private static OutputStream outputStream = null;
  9. private static final UUID uuid = UUID
  10. .fromString("00001101-0000-1000-8000-00805F9B34FB");
  11. private boolean isConnection = false;
  12. final String[] items = { "复位打印机", "标准ASCII字体", "压缩ASCII字体", "字体不放大",
  13. "宽高加倍", "取消加粗模式", "选择加粗模式", "取消倒置打印", "选择倒置打印", "取消黑白反显", "选择黑白反显",
  14. "取消顺时针旋转90°", "选择顺时针旋转90°" };
  15. final byte[][] byteCommands = { { 0x1b, 0x40 },// 复位打印机
  16. { 0x1b, 0x4d, 0x00 },// 标准ASCII字体
  17. { 0x1b, 0x4d, 0x01 },// 压缩ASCII字体
  18. { 0x1d, 0x21, 0x00 },// 字体不放大
  19. { 0x1d, 0x21, 0x11 },// 宽高加倍
  20. { 0x1b, 0x45, 0x00 },// 取消加粗模式
  21. { 0x1b, 0x45, 0x01 },// 选择加粗模式
  22. { 0x1b, 0x7b, 0x00 },// 取消倒置打印
  23. { 0x1b, 0x7b, 0x01 },// 选择倒置打印
  24. { 0x1d, 0x42, 0x00 },// 取消黑白反显
  25. { 0x1d, 0x42, 0x01 },// 选择黑白反显
  26. { 0x1b, 0x56, 0x00 },// 取消顺时针旋转90°
  27. { 0x1b, 0x56, 0x01 },// 选择顺时针旋转90°
  28. };
  29. public PrintDataService(Context context, String deviceAddress) {
  30. super();
  31. this.context = context;
  32. this.deviceAddress = deviceAddress;
  33. this.device = this.bluetoothAdapter.getRemoteDevice(this.deviceAddress);
  34. }
  35. /**
  36. * 获取设备名称
  37. *
  38. * @return String
  39. */
  40. public String getDeviceName() {
  41. return this.device.getName();
  42. }
  43. /**
  44. * 连接蓝牙设备
  45. */
  46. public boolean connect() {
  47. if (!this.isConnection) {
  48. try {
  49. bluetoothSocket = this.device
  50. .createRfcommSocketToServiceRecord(uuid);
  51. bluetoothSocket.connect();
  52. outputStream = bluetoothSocket.getOutputStream();
  53. this.isConnection = true;
  54. if (this.bluetoothAdapter.isDiscovering()) {
  55. System.out.println("关闭适配器!");
  56. this.bluetoothAdapter.isDiscovering();
  57. }
  58. } catch (Exception e) {
  59. Toast.makeText(this.context, "连接失败!", 1).show();
  60. return false;
  61. }
  62. Toast.makeText(this.context, this.device.getName() + "连接成功!",
  63. Toast.LENGTH_SHORT).show();
  64. return true;
  65. } else {
  66. return true;
  67. }
  68. }
  69. /**
  70. * 断开蓝牙设备连接
  71. */
  72. public static void disconnect() {
  73. System.out.println("断开蓝牙设备连接");
  74. try {
  75. bluetoothSocket.close();
  76. outputStream.close();
  77. } catch (IOException e) {
  78. // TODO Auto-generated catch block
  79. e.printStackTrace();
  80. }
  81. }
  82. /**
  83. * 选择指令
  84. */
  85. public void selectCommand() {
  86. new AlertDialog.Builder(context).setTitle("请选择指令")
  87. .setItems(items, new DialogInterface.OnClickListener() {
  88. @Override
  89. public void onClick(DialogInterface dialog, int which) {
  90. try {
  91. outputStream.write(byteCommands[which]);
  92. } catch (IOException e) {
  93. Toast.makeText(context, "设置指令失败!",
  94. Toast.LENGTH_SHORT).show();
  95. }
  96. }
  97. }).create().show();
  98. }
  99. /**
  100. * 发送数据
  101. */
  102. public void send(String sendData) {
  103. if (this.isConnection) {
  104. System.out.println("开始打印!!");
  105. try {
  106. byte[] data = sendData.getBytes("gbk");
  107. outputStream.write(data, 0, data.length);
  108. outputStream.flush();
  109. } catch (IOException e) {
  110. Toast.makeText(this.context, "发送失败!", Toast.LENGTH_SHORT)
  111. .show();
  112. }
  113. } else {
  114. Toast.makeText(this.context, "设备未连接,请重新连接!", Toast.LENGTH_SHORT)
  115. .show();
  116. }
  117. }
  118. }</span>

到此,全部代码贴完,也就大功告成了

对了对了,差点忘记一件很重要的事情!!清单文件忘记给权限啦!!

权限

[html]  view plain copy
  1. <span style="font-size:14px"><uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> </span>

注册Activity

[html]  view plain copy
  1. <span style="font-size:14px"><activity android:name=".BluetoothActivity" />
  2. <activity android:name=".PrintDataActivity" /> </span><span style="font-size:14px">

android 蓝牙打印机相关推荐

  1. android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打印功能进行了封装,让你超快实现蓝牙打印功能

    BluetoothPrint 项目地址:liuGuiRong18/BluetoothPrint  简介:android 蓝牙打印机(ESC/POS 热敏打印机),打印菜单小票和图片,对蓝牙配对和连接打 ...

  2. 蓝牙打印 设置打印样式_GitHub - shen173869710/PrintUtils: Android蓝牙打印机,带你真正了解各种打印格式。...

    PrintUtils Android蓝牙打印机,带你真正了解各种打印格式. 效果图如下: 具体用法是: (1)手机通过蓝牙连接打印机 (2)从BluetoothSocket中getOutputStre ...

  3. android蓝牙打印机

    您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受 目录视图 摘要视图 订阅 CSDN2013年度博客之星 ...

  4. Android蓝牙打印机例子

    上一篇是佳博网络打印机的,这一篇是关于蓝牙(不是低功耗4.0)打印机的例子. /*** 检查是否有纸指令*/public static final byte[] stateBype = new byt ...

  5. Android 蓝牙打印机格式问题

    在项目开发中要用Android手机连接蓝牙打印机,但是数据一直无法上下对齐,在网上各种百度之后,找到了一个方法. 因为我们用的蓝牙打印机编码格式是GBK,所以在向打印机发送消息的时候,要str.get ...

  6. Android蓝牙打印机,带你真正了解各种打印格式

    本文主要讲解蓝牙打印机在打印小票的过程中,如何打印各种常见格式.由于之前需要调试打印格式,但是苦于网上没有详细的讲解教程,无奈只能自给自足,自己封装了一个.如果各位盆友正在或者曾经苦恼蓝牙打印机的打印 ...

  7. Android蓝牙打印机功能开发完整Demo

    蓝牙便携式打印机的种类繁多,支持的打印格式也不尽相同.按照指令集可划分为:ESC指令集.CPCL指令集,实现原理基本相同,我这里以佳博便携式打印机为例,进行蓝牙搜索配对并发送打印数据. 完整代码地址在 ...

  8. android蓝牙打印机打印图片,如何使用打印机(通过蓝牙打印)从Android设备打印图像和一些数据?...

    尝试使用这个-. public class BluetoothPrinterActivity extends Activity { BluetoothAdapter mBTAdapter; Bluet ...

  9. Android蓝牙打印小票,仿美团外卖小票打印

    这个一个Android蓝牙打印小票demo,类似美团外卖小票打印 自适应排版小票格式,一行两列和三列轻松搞定,文本长短不用愁 先看一下效果图: demo里主要是使用汉印打印机进行蓝牙小票打印,它还支持 ...

最新文章

  1. WPF中StringFormat的用法
  2. C# 读取计算机CPU,HDD信息
  3. Supervisor进程管理开机自启
  4. 71道经典Android面试题,涵盖了所有android知识点,值得学习和思考
  5. PCB Genesis脚本 C#调用Javascript
  6. php打印预览jquery,JS实现浏览器打印、打印预览示例
  7. mysql 高并发 优惠券_转 mysql处理高并发,防止库存超卖
  8. 十大必须掌握的 Chrome 浏览器开发者工具
  9. 千兆云路由器Dlink850L10个0Day漏洞成筛子 PoC满天飞 随便拿Root权限
  10. FreeRTOS之源码 及 移植详解
  11. android插件化-apkplug中OSGI服务基本原理-08
  12. 外贸SOHO具备的素质
  13. 文件系统以及硬盘分区概念
  14. gmail无法登陆的解决!!
  15. 《使用Python进行自然语言处理》学习笔记四
  16. caj格式如何转成pdf格式
  17. wps怎么把边框加粗_wps怎么把边框线加粗
  18. 安卓系统高德怎么定位服务器,怎么使用高德地图定位和导航功能?
  19. 炒货币赚钱吗 炒数字货币赚钱吗
  20. js获取元素width和height

热门文章

  1. 当前主要有哪些人在用五笔输入法?
  2. Fiddler 4监听微信浏览器数据
  3. 22.11.14补卡 mysql学习笔记
  4. 以台式计算机主机为例可以分为以下几个部分,《计算机应用基础》基础理论部份.ppt...
  5. 如何将word图片粘贴到TinyMCE里面
  6. 最新Docker hub 国内镜像方法
  7. Python 直接读取 16进制 8进制 整数
  8. 特征提取算法:HOG,HAAR,LBP
  9. 错位排列(java实现)
  10. 我的OpenGL开发日志——枪战游戏