安卓手机连接蓝牙打印机实现打印功能

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

完整源码下载

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

1.这是主界面的效果图

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

[html] view plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  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 plaincopy

  1. <span style="font-size:14px"><activity android:name=".BluetoothActivity" />
  2. <activity android:name=".PrintDataActivity" /> </span><span style="font-size:14px">
  3. </span>

这下子就真的搞定了!

时间: 2024-08-27 13:52:22

安卓手机连接蓝牙打印机实现打印功能的相关文章

Android pad 连接蓝牙打印机Gprinter---实现蓝牙打印功能

一.概述 最近的一个项目有一个需求,要求通过pad的蓝牙去连接l蓝牙打印机去打印单据,就是点击一个按钮去触发生成单据>>保存到数据库 >>蓝牙打印.首先想要实现蓝牙连接,然后去调用Gprinter的SDK,在这里我使用的是Gprinter SDK2.1的版本,而SDK2.2与SDK2.1 的API有不同的地方,这里就以SDK2.1为例. 二.使用 1.首先要导入jar包.添加依赖,如果没有SDK2.1的版本可以去http://download.csdn.net/download/z

进口冷冻品条码采集自动分解出重量并连接蓝牙打印机打印

声明.商业软件,不提供免费下载使用服务. 技术要点: 1,WINCE ppc系统,COM口,超过COM9写法: $device\COM14       ,否则,会提示找不到端口的. 2,蓝牙com端口在程序中,关闭后,不能像电脑一样可以立刻打开,虚拟端口需要一定时间释放资源,一般需要等待20-30秒,否则也会提示找不到端口. 3,手持机上的端口不是随便建立的,这个和硬件有关系,需要手持机厂家决定,大多数是COM6. 4,由于手持机系统不电脑不同,串口数据缓冲有限,再加上蓝牙打印机缓冲更小,所以发

android 连接蓝牙打印机 BluetoothAdapter

android 连接蓝牙打印机 BluetoothAdapter 源码下载地址:https://github.com/yylxy/BluetoothText.git public class PrintActivity extends AppCompatActivity { //设备列表 private ListView listView; private ArrayList<PrintBean> mBluetoothDevicesDatas; private PrintAdapter ada

安卓手机链接window服务器工具。安卓手机连接linux服务器工具

服务器端分为window和类unix 链接类unix工具juicessh 1. 手机搜索juicessh 2. 下载安装软件,以下是安装后界面图,点击链接 3. 输入IP,端口,选择认证方式 4.添加认证 5.点击链接,点击空白区域,出现下图 链接window工具 搜索microsoft远程桌面,也可在APP应用市场搜索下载 打开软件,增加链接 选择desktop,进入增加主机信息页面 选择add 输入主机,端口,用户密码等信息 输入完成保存 原文地址:http://blog.51cto.com

安卓蓝牙实现即时通讯功能

安卓蓝牙实现即时通讯功能 本demo是<Android智能穿戴设备开发指南>书中的一块内容,实现了两台手机基于蓝牙进行即时通讯的功能. demo演示如下: 结构图 主要代码 MainActivity:启动服务器和客户端界面 @Override public void onClick(View arg0) { switch (arg0.getId()) { case R.id.startServerBtn: //打开服务器 Intent serverIntent = new Intent(Mai

【树莓派】树莓派3与手机之间蓝牙连接配置记录

配置树莓派3是支持蓝牙连接的. 这让在进行文件传输,或者音频等都可以使用,可以带来一定的便捷性. 具体怎么做呢?我实践了一下,发现是可以的,下面截取部分相关命令和截图等,供参考. 一.树莓派与手机之间蓝牙配对: 树莓派3直接支持蓝牙,使用直接使用自带命令即可,先打开要连接的蓝牙设备,然后配置树莓派: [email protected]:~ $ sudo bluetoothctl [sudo] password for lifeccp: [NEW] Controller B8:27:EB:F4:4

安卓手机Exchange模式连接邮箱

安卓手机Exchange模式连接邮箱 在企业中,系统管理员经常会遇到同事问手机邮箱怎么配.本说明以小米手机为例,来讲述安卓手机如何配置如何使用Exchage模式连接公司的邮箱,此模式比POP3有诸多优势,在此不细说,最直观的是可以看到全公司同事的邮件地址(Exchange的全球通讯录). 1.1打开程序填写帐号及使用EXCHANGE模式,如下图所示 1.2填写信息以下有几项要注意 用户名:域名\姓名全拼(公司域名china-cmd) 服务器:mail.china-cmd.org(公司对外发布域名

【转】Android打印机--没有设备驱动sdk,自己实现USB打印功能

原文:http://blog.csdn.net/johnwcheung/article/details/71576833 Android下的设备调试,如果设备提供了驱动,按照厂家的驱动调试即可:设备未提供驱动,只能按照通用的方法进行调试. 对于智能POS.收银机以及其他打印设备,如果厂商不提供打印相关sdk,那么打印功能怎么实现呢?其实我们可以基于USB通信机制,自己去实现打印驱动. 整个实现流程如下 初始化打印机:首先要获取USB管理器:其次要注册监听USB设备插拔变化和请求权限的广播:最后列

win10 系统无法通过数据线连接安卓手机,提示无法识别驱动器的解决方案

关于有些人的 win10 系统无法通过数据线连接安卓手机,提示无法识别驱动器,这个问题相信一些android开发者也都遇到过,现整理出自己的解决方案如下(附图): 1.左键点击任务栏右侧的 通知 图标 - 所有设置 - 更新和安全显示界面: 2.在该界面选择左侧恢复,然后在右侧界面点击高级启动 - 立即重启: 3.电脑重启进入选择界面,选择疑难解答并进入界面: 4.点击启动设置,接入界面后选择重启: 5.重启后会进入下面的界面选择红色标记的选项,确定后等待启动完成,然后手机使用数据线连接电脑,下