android蓝牙打印,行业寒冬

64 阅读12分钟
    android:text="打印" />  



<Button  

    android:id="@+id/command"  

    android:layout_width="match_parent"  

    android:layout_height="wrap_content"  

    android:layout_alignParentLeft="true"  

    android:layout_below="@+id/send"  

    android:text="指令" />  

  

  

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



**BluetoothActivity.java**



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



**\[java\]** [view plain]( ) [copy]( ) [print]( ) [?]( )



1.  public class BluetoothActivity extends Activity {    

2.      private Context context = null;    



4.      public void onCreate(Bundle savedInstanceState) {    

5.          super.onCreate(savedInstanceState);    

6.          this.context = this;    

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

8.          setContentView(R.layout.bluetooth\_layout);    

9.          this.initListener();    

10.      }    



12.      private void initListener() {    

13.          ListView unbondDevices = (ListView) this    

14.                  .findViewById(R.id.unbondDevices);    

15.          ListView bondDevices = (ListView) this.findViewById(R.id.bondDevices);    

16.          Button switchBT = (Button) this.findViewById(R.id.openBluetooth\_tb);    

17.          Button searchDevices = (Button) this.findViewById(R.id.searchDevices);    



19.          BluetoothAction bluetoothAction = new BluetoothAction(this.context,    

20.                  unbondDevices, bondDevices, switchBT, searchDevices,    

21.                  BluetoothActivity.this);    



23.          Button returnButton = (Button) this    

24.                  .findViewById(R.id.return\_Bluetooth\_btn);    

25.          bluetoothAction.setSearchDevices(searchDevices);    

26.          bluetoothAction.initView();    



28.          switchBT.setOnClickListener(bluetoothAction);    

29.          searchDevices.setOnClickListener(bluetoothAction);    

30.          returnButton.setOnClickListener(bluetoothAction);    

31.      }    

32.      //屏蔽返回键的代码:    

33.      public boolean onKeyDown(int keyCode,KeyEvent event)    

34.      {    

35.          switch(keyCode)    

36.          {    

37.              case KeyEvent.KEYCODE\_BACK:return true;    

38.          }    

39.          return super.onKeyDown(keyCode, event);    

40.      }    

41.  }  



public class BluetoothActivity extends Activity {

private Context context = null;  



public void onCreate(Bundle savedInstanceState) {  

    super.onCreate(savedInstanceState);  

    this.context = this;  

    setTitle("蓝牙打印");  

    setContentView(R.layout.bluetooth_layout);  

    this.initListener();  

}  



private void initListener() {  

    ListView unbondDevices = (ListView) this  

            .findViewById(R.id.unbondDevices);  

    ListView bondDevices = (ListView) this.findViewById(R.id.bondDevices);  

    Button switchBT = (Button) this.findViewById(R.id.openBluetooth_tb);  

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



    BluetoothAction bluetoothAction = new BluetoothAction(this.context,  

            unbondDevices, bondDevices, switchBT, searchDevices,  

            BluetoothActivity.this);  



    Button returnButton = (Button) this  

            .findViewById(R.id.return_Bluetooth_btn);  

    bluetoothAction.setSearchDevices(searchDevices);  

    bluetoothAction.initView();  



    switchBT.setOnClickListener(bluetoothAction);  

    searchDevices.setOnClickListener(bluetoothAction);  

    returnButton.setOnClickListener(bluetoothAction);  

}  

//屏蔽返回键的代码:  

public boolean onKeyDown(int keyCode,KeyEvent event)  

{  

    switch(keyCode)  

    {  

        case KeyEvent.KEYCODE_BACK:return true;  

    }  

    return super.onKeyDown(keyCode, event);  

}  

}


  

**BluetoothAction.java**  

  



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



  



**\[java\]** [view plain]( ) [copy]( ) [print]( ) [?]( )



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



3.      private Button switchBT = null;    

4.      private Button searchDevices = null;    

5.      private Activity activity = null;    



7.      private ListView unbondDevices = null;    

8.      private ListView bondDevices = null;    

9.      private Context context = null;    

10.      private BluetoothService bluetoothService = null;    



12.      public BluetoothAction(Context context, ListView unbondDevices,    

13.              ListView bondDevices, Button switchBT, Button searchDevices,    

14.              Activity activity) {    

15.          super();    

16.          this.context = context;    

17.          this.unbondDevices = unbondDevices;    

18.          this.bondDevices = bondDevices;    

19.          this.switchBT = switchBT;    

20.          this.searchDevices = searchDevices;    

21.          this.activity = activity;    

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

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

24.                  this.searchDevices);    

25.      }    



27.      public void setSwitchBT(Button switchBT) {    

28.          this.switchBT = switchBT;    

29.      }    



31.      public void setSearchDevices(Button searchDevices) {    

32.          this.searchDevices = searchDevices;    

33.      }    



35.      public void setUnbondDevices(ListView unbondDevices) {    

36.          this.unbondDevices = unbondDevices;    

37.      }    



39.      /\*\*  

40.       \* 初始化界面  

41.       \*/    

42.      public void initView() {    



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

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

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

47.          }    

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

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

50.              this.searchDevices.setEnabled(false);    

51.          }    

52.      }    



54.      private void searchDevices() {    

55.          bluetoothService.searchDevices();    

56.      }    



58.      /\*\*  

59.       \* 各种按钮的监听  

60.       \*/    

61.      @Override    

62.      public void onClick(View v) {    

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

64.              this.searchDevices();    

65.          } else if (v.getId() == R.id.return\_Bluetooth\_btn) {    

66.              activity.finish();    

67.          } else if (v.getId() == R.id.openBluetooth\_tb) {    

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

69.                  // 蓝牙关闭的情况    

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

71.                  this.bluetoothService.openBluetooth(activity);    

72.              } else {    

73.                  // 蓝牙打开的情况    

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

75.                  this.bluetoothService.closeBluetooth();    



77.              }    



79.          }    

80.      }    



82.  }</span>  



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



        }  



    }  

}  

}




  



  



这个类会把各种请求动作分门别类,交给**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<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;    



12.      /\*\*  

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

14.       \*/    

15.      private void addBondDevicesToListView() {    

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

17.          int count = this.bondDevices.size();    

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

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

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

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

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

23.          }    

24.          String\[\] from = { "deviceName" };    

25.          int\[\] to = { R.id.device\_name };    

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

27.                  R.layout.bonddevice\_item, from, to);    

28.          // 把适配器装载到listView中    

29.          this.bondDevicesListView.setAdapter(simpleAdapter);    



31.          this.bondDevicesListView    

32.                  .setOnItemClickListener(new OnItemClickListener() {    



34.                      @Override    

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

36.                              int arg2, long arg3) {    

37.                          BluetoothDevice device = bondDevices.get(arg2);    

38.                          Intent intent = new Intent();    

39.                          intent.setClassName(context,    

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

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

42.                          context.startActivity(intent);    

43.                      }    

44.                  });    



46.      }    



48.      /\*\*  

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

50.       \*/    

51.      private void addUnbondDevicesToListView() {    

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

53.          int count = this.unbondDevices.size();    

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

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

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

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

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

59.          }    

60.          String\[\] from = { "deviceName" };    

61.          int\[\] to = { R.id.device\_name };    

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

63.                  R.layout.unbonddevice\_item, from, to);    



65.          // 把适配器装载到listView中    

66.          this.unbondDevicesListView.setAdapter(simpleAdapter);    



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

69.          this.unbondDevicesListView    

70.                  .setOnItemClickListener(new OnItemClickListener() {    



72.                      @Override    

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

74.                              int arg2, long arg3) {    

75.                          try {    

76.                              Method createBondMethod = BluetoothDevice.class    

77.                                      .getMethod("createBond");    

78.                              createBondMethod    

79.                                      .invoke(unbondDevices.get(arg2));    

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

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

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

83.                              unbondDevices.remove(arg2);    

84.                              addBondDevicesToListView();    

85.                              addUnbondDevicesToListView();    

86.                          } catch (Exception e) {    

87.                              Toast.makeText(context, "配对失败!", Toast.LENGTH\_SHORT)    

88.                                      .show();    

89.                          }    



91.                      }    

92.                  });    

93.      }    



95.      public BluetoothService(Context context, ListView unbondDevicesListView,    

96.              ListView bondDevicesListView, Button switchBT, Button searchDevices) {    

97.          this.context = context;    

98.          this.unbondDevicesListView = unbondDevicesListView;    

99.          this.bondDevicesListView = bondDevicesListView;    

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

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

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

103.          this.switchBT = switchBT;    

104.          this.searchDevices = searchDevices;    

105.          this.initIntentFilter();    



107.      }    



109.      private void initIntentFilter() {    

110.          // 设置广播信息过滤    

111.          IntentFilter intentFilter = new IntentFilter();    

112.          intentFilter.addAction(BluetoothDevice.ACTION\_FOUND);    

113.          intentFilter.addAction(BluetoothAdapter.ACTION\_DISCOVERY\_STARTED);    

114.          intentFilter.addAction(BluetoothAdapter.ACTION\_DISCOVERY\_FINISHED);    

115.          intentFilter.addAction(BluetoothAdapter.ACTION\_STATE\_CHANGED);    

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

117.          context.registerReceiver(receiver, intentFilter);    



119.      }    



121.      /\*\*  

122.       \* 打开蓝牙  

123.       \*/    

124.      public void openBluetooth(Activity activity) {    

125.          Intent enableBtIntent = new Intent(    

126.                  BluetoothAdapter.ACTION\_REQUEST\_ENABLE);    

127.          activity.startActivityForResult(enableBtIntent, 1);    



129.      }    



131.      /\*\*  

132.       \* 关闭蓝牙  

133.       \*/    

134.      public void closeBluetooth() {    

135.          this.bluetoothAdapter.disable();    

136.      }    



138.      /\*\*  

139.       \* 判断蓝牙是否打开  

140.       \*   

141.       \* @return boolean  

142.       \*/    

143.      public boolean isOpen() {    

144.          return this.bluetoothAdapter.isEnabled();    



146.      }    



148.      /\*\*  

149.       \* 搜索蓝牙设备  

150.       \*/    

151.      public void searchDevices() {    

152.          this.bondDevices.clear();    

153.          this.unbondDevices.clear();    



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

156.          this.bluetoothAdapter.startDiscovery();    

157.      }    



159.      /\*\*  

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

161.       \*   

162.       \* @param device  

163.       \*/    

164.      public void addUnbondDevices(BluetoothDevice device) {    

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

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

167.              this.unbondDevices.add(device);    

168.          }    

169.      }    



171.      /\*\*  

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

173.       \*   

174.       \* @param device  

175.       \*/    

176.      public void addBandDevices(BluetoothDevice device) {    

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

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

179.              this.bondDevices.add(device);    

180.          }    

181.      }    



183.      /\*\*  

184.       \* 蓝牙广播接收器  

185.       \*/    

186.      private BroadcastReceiver receiver = new BroadcastReceiver() {    



188.          ProgressDialog progressDialog = null;    



190.          @Override    

191.          public void onReceive(Context context, Intent intent) {    

192.              String action = intent.getAction();    

193.              if (BluetoothDevice.ACTION\_FOUND.equals(action)) {    

194.                  BluetoothDevice device = intent    

195.                          .getParcelableExtra(BluetoothDevice.EXTRA\_DEVICE);    

196.                  if (device.getBondState() == BluetoothDevice.BOND\_BONDED) {    

197.                      addBandDevices(device);    

198.                  } else {    

199.                      addUnbondDevices(device);    

200.                  }    

201.              } else if (BluetoothAdapter.ACTION\_DISCOVERY\_STARTED.equals(action)) {    

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

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



205.              } else if (BluetoothAdapter.ACTION\_DISCOVERY\_FINISHED    

206.                      .equals(action)) {    

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

208.                  progressDialog.dismiss();    



210.                  addUnbondDevicesToListView();    

211.                  addBondDevicesToListView();    

212.                  // bluetoothAdapter.cancelDiscovery();    

213.              }    

214.              if (BluetoothAdapter.ACTION\_STATE\_CHANGED.equals(action)) {    

215.                  if (bluetoothAdapter.getState() == BluetoothAdapter.STATE\_ON) {    

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

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

218.                      searchDevices.setEnabled(true);    

219.                      bondDevicesListView.setEnabled(true);    

220.                      unbondDevicesListView.setEnabled(true);    

221.                  } else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE\_OFF) {    

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

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

224.                      searchDevices.setEnabled(false);    

225.                      bondDevicesListView.setEnabled(false);    

226.                      unbondDevicesListView.setEnabled(false);    

227.                  }    

228.              }    



230.          }    



232.      };    



234.  }  



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;    



4.      public void onCreate(Bundle savedInstanceState) {    

5.          super.onCreate(savedInstanceState);    

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

7.          this.setContentView(R.layout.printdata\_layout);    

8.          this.context = this;    

9.          this.initListener();    

10.      }    



12.      /\*\*  

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

14.       \* @return String  

15.       \*/    

16.      private String getDeviceAddress() {    

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

18.          Intent intent = this.getIntent();    

19.          // 判断    

20.          if (intent != null) {    

21.              return intent.getStringExtra("deviceAddress");    

22.          } else {    

23.              return null;    

24.          }    

25.      }    



27.      private void initListener() {    

28.          TextView deviceName = (TextView) this.findViewById(R.id.device\_name);    

29.          TextView connectState = (TextView) this    

30.                  .findViewById(R.id.connect\_state);    



32.          PrintDataAction printDataAction = new PrintDataAction(this.context,    

33.                  this.getDeviceAddress(), deviceName, connectState);    



35.          EditText printData = (EditText) this.findViewById(R.id.print\_data);    

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

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

38.          printDataAction.setPrintData(printData);    



40.          send.setOnClickListener(printDataAction);    

41.          command.setOnClickListener(printDataAction);    

42.      }    



45.      @Override    

46.      protected void onDestroy() {    

47.          PrintDataService.disconnect();    

48.          super.onDestroy();    

49.      }    



51.  }  



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;    



9.      public PrintDataAction(Context context, String deviceAddress,    

10.              TextView deviceName, TextView connectState) {    

11.          super();    

12.          this.context = context;    

13.          this.deviceAddress = deviceAddress;    

14.          this.deviceName = deviceName;    

15.          this.connectState = connectState;    

16.          this.printDataService = new PrintDataService(this.context,    

17.                  this.deviceAddress);    

18.          this.initView();    



20.      }    



22.      private void initView() {    

23.          // 设置当前设备名称    

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

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

26.          boolean flag = this.printDataService.connect();    

27.          if (flag == false) {    

28.              // 连接失败    

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

30.          } else {    

31.              // 连接成功    

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



34.          }    

35.      }    



37.      public void setPrintData(EditText printData) {    

38.          this.printData = printData;    

39.      }    



41.      @Override    

42.      public void onClick(View v) {    

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

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

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

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

47.              this.printDataService.selectCommand();    



49.          }    

50.      }    

51.  }</span>  



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



    }  

}  

}


  

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;    

### 总结

最后为了帮助大家深刻理解Android相关知识点的原理以及面试相关知识,这里放上相关的我搜集整理的14套腾讯、字节跳动、阿里、百度等[2020面试真题解析](https://github.com/a120464/Android-P7/blob/master/Android%E5%BC%80%E5%8F%91%E4%B8%8D%E4%BC%9A%E8%BF%99%E4%BA%9B%EF%BC%9F%E5%A6%82%E4%BD%95%E9%9D%A2%E8%AF%95%E6%8B%BF%E9%AB%98%E8%96%AA%EF%BC%81.md),我把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包知识脉络 + 诸多细节。

![2020面试真题解析](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/47171f1fef9e49a88d7efce51a13e923~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3MDY4Mzc0MTQxMzQ0:q75.awebp?rk3s=f64ab15b&x-expires=1771286463&x-signature=d8vseyvbLmFEDmp%2F8T%2F4kdUHnhE%3D)
![腾讯面试真题解析](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/401dc4538bd24eec9c65e75cebe26382~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3MDY4Mzc0MTQxMzQ0:q75.awebp?rk3s=f64ab15b&x-expires=1771286463&x-signature=Tv9LCvW%2FsAnJhXJDnOjNO6bf%2BtA%3D)

![阿里巴巴面试真题解析](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/ab40675c83eb4a31a5ad3a028b44aae9~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3MDY4Mzc0MTQxMzQ0:q75.awebp?rk3s=f64ab15b&x-expires=1771286463&x-signature=JHlaHhxUqpu47n%2B%2FWxWQtDp5x8A%3D)

![字节跳动面试真题解析](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/a5cbea99f2984f2d85549a01db27ad89~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3MDY4Mzc0MTQxMzQ0:q75.awebp?rk3s=f64ab15b&x-expires=1771286463&x-signature=oyGKrFFSGGJdjX%2B9vdAfbPTrpEA%3D)
网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份[系统化的技术体系](https://github.com/a120464/Android-P7/blob/master/Android%E5%BC%80%E5%8F%91%E4%B8%8D%E4%BC%9A%E8%BF%99%E4%BA%9B%EF%BC%9F%E5%A6%82%E4%BD%95%E9%9D%A2%E8%AF%95%E6%8B%BF%E9%AB%98%E8%96%AA%EF%BC%81.md)对大家有一个方向参考。

![](https://p9-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/debbe2032ce9473ca433ba996f825a2b~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg55So5oi3MDY4Mzc0MTQxMzQ0:q75.awebp?rk3s=f64ab15b&x-expires=1771286463&x-signature=b469kq%2B9n1REiReVFLp1kBD5%2B%2Fo%3D)