2024年Android最全android蓝牙打印(1),2024年最新通过五轮面试斩获offer阿里实习生亲述

最后

如果你看到了这里,觉得文章写得不错就给个赞呗?如果你觉得那里值得改进的,请给我留言。一定会认真查询,修正不足。谢谢。

最后针对Android程序员,我这边给大家整理了一些资料,包括不限于高级UI、性能优化、移动架构师、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter等全方面的Android进阶实践技术;希望能帮助到大家,也节省大家在网上搜索资料的时间来学习,也可以分享动态给身边好友一起学习!

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  1. ListView bondDevices, Button switchBT, Button searchDevices,

  2. Activity activity) {

  3. super();

  4. this.context = context;

  5. this.unbondDevices = unbondDevices;

  6. this.bondDevices = bondDevices;

  7. this.switchBT = switchBT;

  8. this.searchDevices = searchDevices;

  9. this.activity = activity;

  10. this.bluetoothService = new BluetoothService(this.context,

  11. this.unbondDevices, this.bondDevices, this.switchBT,

  12. this.searchDevices);

  13. }

  14. public void setSwitchBT(Button switchBT) {

  15. this.switchBT = switchBT;

  16. }

  17. public void setSearchDevices(Button searchDevices) {

  18. this.searchDevices = searchDevices;

  19. }

  20. public void setUnbondDevices(ListView unbondDevices) {

  21. this.unbondDevices = unbondDevices;

  22. }

  23. /**

  24. * 初始化界面

  25. */

  26. public void initView() {

  27. if (this.bluetoothService.isOpen()) {

  28. System.out.println(“蓝牙有开!”);

  29. switchBT.setText(“关闭蓝牙”);

  30. }

  31. if (!this.bluetoothService.isOpen()) {

  32. System.out.println(“蓝牙没开!”);

  33. this.searchDevices.setEnabled(false);

  34. }

  35. }

  36. private void searchDevices() {

  37. bluetoothService.searchDevices();

  38. }

  39. /**

  40. * 各种按钮的监听

  41. */

  42. @Override

  43. public void onClick(View v) {

  44. if (v.getId() == R.id.searchDevices) {

  45. this.searchDevices();

  46. } else if (v.getId() == R.id.return_Bluetooth_btn) {

  47. activity.finish();

  48. } else if (v.getId() == R.id.openBluetooth_tb) {

  49. if (!this.bluetoothService.isOpen()) {

  50. // 蓝牙关闭的情况

  51. System.out.println(“蓝牙关闭的情况”);

  52. this.bluetoothService.openBluetooth(activity);

  53. } else {

  54. // 蓝牙打开的情况

  55. System.out.println(“蓝牙打开的情况”);

  56. this.bluetoothService.closeBluetooth();

  57. }

  58. }

  59. }

  60. }


<span style="font-size: 14px;">public class BluetoothAction implements OnClickListener {  

  

    private Button switchBT = null;  

    private Button searchDevices = null;  

    private Activity activity = null;  

  

    private ListView unbondDevices = null;  

    private ListView bondDevices = null;  

    private Context context = null;  

    private BluetoothService bluetoothService = null;  

  

    public BluetoothAction(Context context, ListView unbondDevices,  

            ListView bondDevices, Button switchBT, Button searchDevices,  

            Activity activity) {  

        super();  

        this.context = context;  

        this.unbondDevices = unbondDevices;  

        this.bondDevices = bondDevices;  

        this.switchBT = switchBT;  

        this.searchDevices = searchDevices;  

        this.activity = activity;  

        this.bluetoothService = new BluetoothService(this.context,  

                this.unbondDevices, this.bondDevices, this.switchBT,  

                this.searchDevices);  

    }  

  

    public void setSwitchBT(Button switchBT) {  

        this.switchBT = switchBT;  

    }  

  

    public void setSearchDevices(Button searchDevices) {  

        this.searchDevices = searchDevices;  

    }  

  

    public void setUnbondDevices(ListView unbondDevices) {  

        this.unbondDevices = unbondDevices;  

    }  

  

    /** 

     * 初始化界面 

     */  

    public void initView() {  

  

        if (this.bluetoothService.isOpen()) {  

            System.out.println("蓝牙有开!");  

            switchBT.setText("关闭蓝牙");  

        }  

        if (!this.bluetoothService.isOpen()) {  

            System.out.println("蓝牙没开!");  

            this.searchDevices.setEnabled(false);  

        }  

    }  

  

    private void searchDevices() {  

        bluetoothService.searchDevices();  

    }  

  

    /** 

     * 各种按钮的监听 

     */  

    @Override  

    public void onClick(View v) {  

        if (v.getId() == R.id.searchDevices) {  

            this.searchDevices();  

        } else if (v.getId() == R.id.return_Bluetooth_btn) {  

            activity.finish();  

        } else if (v.getId() == R.id.openBluetooth_tb) {  

            if (!this.bluetoothService.isOpen()) {  

                // 蓝牙关闭的情况  

                System.out.println("蓝牙关闭的情况");  

                this.bluetoothService.openBluetooth(activity);  

            } else {  

                // 蓝牙打开的情况  

                System.out.println("蓝牙打开的情况");  

                this.bluetoothService.closeBluetooth();  

  

            }  

  

        }  

    }  

  

}</span>

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

[java] view plain copy print ?

  1. public class BluetoothService {

  2. private Context context = null;

  3. private BluetoothAdapter bluetoothAdapter = BluetoothAdapter

  4. .getDefaultAdapter();

  5. private ArrayList unbondDevices = null; // 用于存放未配对蓝牙设备

  6. private ArrayList 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();

  92. this.bondDevices = new ArrayList();

  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. }


public class BluetoothService {  

    private Context context = null;  

    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter  

            .getDefaultAdapter();  

    private ArrayList<BluetoothDevice> unbondDevices = null; // 用于存放未配对蓝牙设备  

    private ArrayList<BluetoothDevice> bondDevices = null;// 用于存放已配对蓝牙设备  

    private Button switchBT = null;  

    private Button searchDevices = null;  

    private ListView unbondDevicesListView = null;  

    private ListView bondDevicesListView = null;  

  

    /** 

     * 添加已绑定蓝牙设备到ListView 

     */  

    private void addBondDevicesToListView() {  

        ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  

        int count = this.bondDevices.size();  

        System.out.println("已绑定设备数量:" + count);  

        for (int i = 0; i < count; i++) {  

            HashMap<String, Object> map = new HashMap<String, Object>();  

            map.put("deviceName", this.bondDevices.get(i).getName());  

            data.add(map);// 把item项的数据加到data中  

        }  

        String[] from = { "deviceName" };  

        int[] to = { R.id.device_name };  

        SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,  

                R.layout.bonddevice_item, from, to);  

        // 把适配器装载到listView中  

        this.bondDevicesListView.setAdapter(simpleAdapter);  

  

        this.bondDevicesListView  

                .setOnItemClickListener(new OnItemClickListener() {  

  

                    @Override  

                    public void onItemClick(AdapterView<?> arg0, View arg1,  

                            int arg2, long arg3) {  

                        BluetoothDevice device = bondDevices.get(arg2);  

                        Intent intent = new Intent();  

                        intent.setClassName(context,  

                                "com.lifeng.jdxt.view.PrintDataActivity");  

                        intent.putExtra("deviceAddress", device.getAddress());  

                        context.startActivity(intent);  

                    }  

                });  

  

    }  

  

    /** 

     * 添加未绑定蓝牙设备到ListView 

     */  

    private void addUnbondDevicesToListView() {  

        ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();  

        int count = this.unbondDevices.size();  

        System.out.println("未绑定设备数量:" + count);  

        for (int i = 0; i < count; i++) {  

            HashMap<String, Object> map = new HashMap<String, Object>();  

            map.put("deviceName", this.unbondDevices.get(i).getName());  

            data.add(map);// 把item项的数据加到data中  

        }  

        String[] from = { "deviceName" };  

        int[] to = { R.id.device_name };  

        SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data,  

                R.layout.unbonddevice_item, from, to);  

  

        // 把适配器装载到listView中  

        this.unbondDevicesListView.setAdapter(simpleAdapter);  

  

        // 为每个item绑定监听,用于设备间的配对  

        this.unbondDevicesListView  

                .setOnItemClickListener(new OnItemClickListener() {  

  

                    @Override  

                    public void onItemClick(AdapterView<?> arg0, View arg1,  

                            int arg2, long arg3) {  

                        try {  

                            Method createBondMethod = BluetoothDevice.class  

                                    .getMethod("createBond");  

                            createBondMethod  

                                    .invoke(unbondDevices.get(arg2));  

                            // 将绑定好的设备添加的已绑定list集合  

                            bondDevices.add(unbondDevices.get(arg2));  

                            // 将绑定好的设备从未绑定list集合中移除  

                            unbondDevices.remove(arg2);  

                            addBondDevicesToListView();  

                            addUnbondDevicesToListView();  

                        } catch (Exception e) {  

                            Toast.makeText(context, "配对失败!", Toast.LENGTH_SHORT)  

                                    .show();  

                        }  

  

                    }  

                });  

    }  

  

    public BluetoothService(Context context, ListView unbondDevicesListView,  

            ListView bondDevicesListView, Button switchBT, Button searchDevices) {  

        this.context = context;  

        this.unbondDevicesListView = unbondDevicesListView;  

        this.bondDevicesListView = bondDevicesListView;  

        // this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();  

        this.unbondDevices = new ArrayList<BluetoothDevice>();  

        this.bondDevices = new ArrayList<BluetoothDevice>();  

        this.switchBT = switchBT;  

        this.searchDevices = searchDevices;  

        this.initIntentFilter();  

  

    }  

  

    private void initIntentFilter() {  

        // 设置广播信息过滤  

        IntentFilter intentFilter = new IntentFilter();  

        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);  

        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);  

        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  

        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);  

        // 注册广播接收器,接收并处理搜索结果  

        context.registerReceiver(receiver, intentFilter);  

  

    }  

  

    /** 

     * 打开蓝牙 

     */  

    public void openBluetooth(Activity activity) {  

        Intent enableBtIntent = new Intent(  

                BluetoothAdapter.ACTION_REQUEST_ENABLE);  

        activity.startActivityForResult(enableBtIntent, 1);  

  

    }  

  

    /** 

     * 关闭蓝牙 

     */  

    public void closeBluetooth() {  

        this.bluetoothAdapter.disable();  

    }  

  

    /** 

     * 判断蓝牙是否打开 

     *  

     * @return boolean 

     */  

    public boolean isOpen() {  

        return this.bluetoothAdapter.isEnabled();  

  

    }  

  

    /** 

     * 搜索蓝牙设备 

     */  

    public void searchDevices() {  

        this.bondDevices.clear();  

        this.unbondDevices.clear();  

  

        // 寻找蓝牙设备,android会将查找到的设备以广播形式发出去  

        this.bluetoothAdapter.startDiscovery();  

    }  

  

    /** 

     * 添加未绑定蓝牙设备到list集合 

     *  

     * @param device 

     */  

    public void addUnbondDevices(BluetoothDevice device) {  

        System.out.println("未绑定设备名称:" + device.getName());  

        if (!this.unbondDevices.contains(device)) {  

            this.unbondDevices.add(device);  

        }  

    }  

  

    /** 

     * 添加已绑定蓝牙设备到list集合 

     *  

     * @param device 

     */  

    public void addBandDevices(BluetoothDevice device) {  

        System.out.println("已绑定设备名称:" + device.getName());  

        if (!this.bondDevices.contains(device)) {  

            this.bondDevices.add(device);  

        }  

    }  

  

    /** 

     * 蓝牙广播接收器 

     */  

    private BroadcastReceiver receiver = new BroadcastReceiver() {  

  

        ProgressDialog progressDialog = null;  

  

        @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);  

                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {  

                    addBandDevices(device);  

                } else {  

                    addUnbondDevices(device);  

                }  

            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {  

                progressDialog = ProgressDialog.show(context, "请稍等...",  

                        "搜索蓝牙设备中...", true);  

  

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED  

                    .equals(action)) {  

                System.out.println("设备搜索完毕");  

                progressDialog.dismiss();  

  

                addUnbondDevicesToListView();  

                addBondDevicesToListView();  

                // bluetoothAdapter.cancelDiscovery();  

            }  

            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {  

                if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {  

                    System.out.println("--------打开蓝牙-----------");  

                    switchBT.setText("关闭蓝牙");  

                    searchDevices.setEnabled(true);  

                    bondDevicesListView.setEnabled(true);  

                    unbondDevicesListView.setEnabled(true);  

                } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {  

                    System.out.println("--------关闭蓝牙-----------");  

                    switchBT.setText("打开蓝牙");  

                    searchDevices.setEnabled(false);  

                    bondDevicesListView.setEnabled(false);  

                    unbondDevicesListView.setEnabled(false);  

                }  

            }  

  

        }  

  

    };  

  

}

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

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

PrintDataActivity.java

[java] view plain copy print ?

  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. }


public class PrintDataActivity extends Activity {  

    private Context context = null;  

  

    public void onCreate(Bundle savedInstanceState) {  

        super.onCreate(savedInstanceState);  

        this.setTitle("蓝牙打印");  

        this.setContentView(R.layout.printdata_layout);  

        this.context = this;  

        this.initListener();  

    }  

  

    /** 

     * 获得从上一个Activity传来的蓝牙地址 

     * @return String 

     */  

    private String getDeviceAddress() {  

        // 直接通过Context类的getIntent()即可获取Intent  

        Intent intent = this.getIntent();  

        // 判断  

        if (intent != null) {  

            return intent.getStringExtra("deviceAddress");  

        } else {  

            return null;  

        }  

    }  

  

    private void initListener() {  

        TextView deviceName = (TextView) this.findViewById(R.id.device_name);  

        TextView connectState = (TextView) this  

                .findViewById(R.id.connect_state);  

  

        PrintDataAction printDataAction = new PrintDataAction(this.context,  

                this.getDeviceAddress(), deviceName, connectState);  

  

        EditText printData = (EditText) this.findViewById(R.id.print_data);  

        Button send = (Button) this.findViewById(R.id.send);  

        Button command = (Button) this.findViewById(R.id.command);  

        printDataAction.setPrintData(printData);  

  

        send.setOnClickListener(printDataAction);  

        command.setOnClickListener(printDataAction);  

    }  

  

      

    @Override  

    protected void onDestroy() {  

        PrintDataService.disconnect();  

        super.onDestroy();  

    }  

      

}

PrintDataAction.java

[java] view plain copy print ?

  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 style="font-size: 14px;">public class PrintDataAction implements OnClickListener {  

    private Context context = null;  

    private TextView deviceName = null;  

    private TextView connectState = null;  

    private EditText printData = null;  

    private String deviceAddress = null;  

    private PrintDataService printDataService = null;  

  

    public PrintDataAction(Context context, String deviceAddress,  

            TextView deviceName, TextView connectState) {  

        super();  

        this.context = context;  

        this.deviceAddress = deviceAddress;  

        this.deviceName = deviceName;  

        this.connectState = connectState;  

        this.printDataService = new PrintDataService(this.context,  

                this.deviceAddress);  

        this.initView();  

  

    }  

  

    private void initView() {  

        // 设置当前设备名称  

        this.deviceName.setText(this.printDataService.getDeviceName());  

        // 一上来就先连接蓝牙设备  

        boolean flag = this.printDataService.connect();  

        if (flag == false) {  

            // 连接失败  

            this.connectState.setText("连接失败!");  

        } else {  

            // 连接成功  

            this.connectState.setText("连接成功!");  

  

        }  

    }  

  

    public void setPrintData(EditText printData) {  

        this.printData = printData;  

    }  

  

    @Override  

    public void onClick(View v) {  

        if (v.getId() == R.id.send) {  

            String sendData = this.printData.getText().toString();  

            this.printDataService.send(sendData + "\n");  

        } else if (v.getId() == R.id.command) {  

            this.printDataService.selectCommand();  

  

        }  

    }  

}</span>

PrintDataService.java

[java] view plain copy print ?

  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 style="font-size: 14px;">public class PrintDataService {  

    private Context context = null;  



## 最后

**分享一份工作1到5年以上的Android程序员架构进阶学习路线体系,希望能对那些还在从事Android开发却还不知道如何去提升自己的,还处于迷茫的朋友!**

* 阿里P7级Android架构师技术脑图;查漏补缺,体系化深入学习提升

  ![](https://img-blog.csdnimg.cn/img_convert/4b66a74fc3d5a5c01bb7a8356e1b97bd.webp?x-oss-process=image/format,png)
* **全套体系化高级架构视频;**七大主流技术模块,视频+源码+笔记

![](https://img-blog.csdnimg.cn/img_convert/888386f378079c89130cb980f26a5c03.webp?x-oss-process=image/format,png)

有任何问题,欢迎广大网友一起来交流




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618156601)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

ialog, int which) {    

96.                          try {    

97.                              outputStream.write(byteCommands\[which\]);    

98.                          } catch (IOException e) {    

99.                              Toast.makeText(context, "设置指令失败!",    

100.                                      Toast.LENGTH\_SHORT).show();    

101.                          }    

102.                      }    

103.                  }).create().show();    

104.      }    



106.      /\*\*  

107.       \* 发送数据  

108.       \*/    

109.      public void send(String sendData) {    

110.          if (this.isConnection) {    

111.              System.out.println("开始打印!!");    

112.              try {    

113.                  byte\[\] data = sendData.getBytes("gbk");    

114.                  outputStream.write(data, 0, data.length);    

115.                  outputStream.flush();    

116.              } catch (IOException e) {    

117.                  Toast.makeText(this.context, "发送失败!", Toast.LENGTH\_SHORT)    

118.                          .show();    

119.              }    

120.          } else {    

121.              Toast.makeText(this.context, "设备未连接,请重新连接!", Toast.LENGTH\_SHORT)    

122.                      .show();    



124.          }    

125.      }    



127.  }</span>  



public class PrintDataService {

private Context context = null;  

最后

分享一份工作1到5年以上的Android程序员架构进阶学习路线体系,希望能对那些还在从事Android开发却还不知道如何去提升自己的,还处于迷茫的朋友!

  • 阿里P7级Android架构师技术脑图;查漏补缺,体系化深入学习提升

    [外链图片转存中…(img-sc4GlDVt-1715618785969)]

  • **全套体系化高级架构视频;**七大主流技术模块,视频+源码+笔记

[外链图片转存中…(img-2cvG3VVa-1715618785970)]

有任何问题,欢迎广大网友一起来交流

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化学习资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 12
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值