最近在做一個安卓應用,其中有一個需求是要求用藍牙連接打印機實現打印功能。一開始沒有一點頭緒,網上找了很多資料也找不到有用的數據。所以自己就去研究,最終,功夫不負有心人,順利的完成了這個功能。下邊貼出我寫的代碼,共有需要的IT哥們參考學習。
我們先看看運行效果圖吧。。。
1.這是主界面的效果圖
貼上布局文件的代碼:bluetooth_layout.xml
- <span style="font-size:12px"><?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <Button
- android:id="@+id/openBluetooth_tb"
- android:layout_width="130dp"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_marginRight="18dp"
- android:layout_marginTop="5dp"
- android:text="打開藍牙" />
- <Button
- android:id="@+id/searchDevices"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/openBluetooth_tb"
- android:layout_marginTop="20dp"
- android:text="搜索設備" />
- <View
- android:layout_width="match_parent"
- android:layout_height="3dp"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/searchDevices"
- android:background="@android:color/darker_gray" />
- <LinearLayout
- android:id="@+id/linearLayout1"
- android:layout_width="match_parent"
- android:layout_height="150dp"
- android:layout_marginTop="125dp"
- android:orientation="vertical" >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="未配對設備" />
- <ListView
- android:id="@+id/unbondDevices"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </LinearLayout>
- <View
- android:layout_width="match_parent"
- android:layout_height="3dp"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/searchDevices"
- android:layout_marginTop="160dp"
- android:background="@android:color/darker_gray" />
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="190dp"
- android:layout_marginTop="288dp"
- android:orientation="vertical" >
- <TextView
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="已配對設備" />
- <ListView
- android:id="@+id/bondDevices"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/linearLayout1" >
- </ListView>
- </LinearLayout>
- <Button
- android:id="@+id/return_Bluetooth_btn"
- android:layout_width="100dp"
- android:layout_height="wrap_content"
- android:layout_above="@+id/searchDevices"
- android:layout_alignParentLeft="true"
- android:text="返回" />
- </RelativeLayout></span>
從上邊的布局文件中不難看出,其中有兩個ListView,OK,那下邊貼出對應的兩個item布局文件
--> 第一個item:unbonddevice_item.xml
- <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TextView
- android:id="@+id/device_name"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="未綁定設備"
- android:textAppearance="?android:attr/textAppearanceLarge" />
- </RelativeLayout></span>
-->第二個item:bonddevice_item.xml
- <span style="font-size:14px"><?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <TextView
- android:id="@+id/device_name"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="已綁定設備"
- android:textAppearance="?android:attr/textAppearanceLarge" />
- </RelativeLayout></span>
2.還有另外一個布局文件,就是當點擊已綁定藍牙設備下邊的某個item時進入打印的界面,不多說,看圖!
代碼如下:printdata_layout.xml
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
- <EditText
- android:id="@+id/print_data"
- android:layout_width="match_parent"
- android:layout_height="200dp"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginTop="46dp" >
- </EditText>
- <TextView
- android:id="@+id/device_name"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginTop="16dp"
- android:text="Large Text"
- android:textAppearance="?android:attr/textAppearanceLarge" />
- <TextView
- android:id="@+id/connect_state"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/device_name"
- android:layout_alignBottom="@+id/device_name"
- android:layout_marginLeft="42dp"
- android:layout_toRightOf="@+id/device_name"
- android:text="Large Text"
- android:textAppearance="?android:attr/textAppearanceLarge" />
- <Button
- android:id="@+id/send"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/print_data"
- android:layout_marginTop="21dp"
- 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="指令" />
- </RelativeLayout>
至此,布局文件就搞定了,接下來就要編寫java代碼了。主要有一下這么幾個類,一個一個來哈
BluetoothActivity.java
這個類的主要作用是初始化主界面,看代碼
- 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類,看代碼
- <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來處理,看代碼
- 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
- 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
- <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
- <span style="font-size:14px">public class PrintDataService {
- private Context context = null;
- private String deviceAddress = null;
- private BluetoothAdapter bluetoothAdapter = BluetoothAdapter
- .getDefaultAdapter();
- private BluetoothDevice device = null;
- private static BluetoothSocket bluetoothSocket = null;
- private static OutputStream outputStream = null;
- private static final UUID uuid = UUID
- .fromString("00001101-0000-1000-8000-00805F9B34FB");
- private boolean isConnection = false;
- final String[] items = { "復位打印機", "標准ASCII字體", "壓縮ASCII字體", "字體不放大",
- "寬高加倍", "取消加粗模式", "選擇加粗模式", "取消倒置打印", "選擇倒置打印", "取消黑白反顯", "選擇黑白反顯",
- "取消順時針旋轉90°", "選擇順時針旋轉90°" };
- final byte[][] byteCommands = { { 0x1b, 0x40 },// 復位打印機
- { 0x1b, 0x4d, 0x00 },// 標准ASCII字體
- { 0x1b, 0x4d, 0x01 },// 壓縮ASCII字體
- { 0x1d, 0x21, 0x00 },// 字體不放大
- { 0x1d, 0x21, 0x11 },// 寬高加倍
- { 0x1b, 0x45, 0x00 },// 取消加粗模式
- { 0x1b, 0x45, 0x01 },// 選擇加粗模式
- { 0x1b, 0x7b, 0x00 },// 取消倒置打印
- { 0x1b, 0x7b, 0x01 },// 選擇倒置打印
- { 0x1d, 0x42, 0x00 },// 取消黑白反顯
- { 0x1d, 0x42, 0x01 },// 選擇黑白反顯
- { 0x1b, 0x56, 0x00 },// 取消順時針旋轉90°
- { 0x1b, 0x56, 0x01 },// 選擇順時針旋轉90°
- };
- public PrintDataService(Context context, String deviceAddress) {
- super();
- this.context = context;
- this.deviceAddress = deviceAddress;
- this.device = this.bluetoothAdapter.getRemoteDevice(this.deviceAddress);
- }
- /**
- * 獲取設備名稱
- *
- * @return String
- */
- public String getDeviceName() {
- return this.device.getName();
- }
- /**
- * 連接藍牙設備
- */
- public boolean connect() {
- if (!this.isConnection) {
- try {
- bluetoothSocket = this.device
- .createRfcommSocketToServiceRecord(uuid);
- bluetoothSocket.connect();
- outputStream = bluetoothSocket.getOutputStream();
- this.isConnection = true;
- if (this.bluetoothAdapter.isDiscovering()) {
- System.out.println("關閉適配器!");
- this.bluetoothAdapter.isDiscovering();
- }
- } catch (Exception e) {
- Toast.makeText(this.context, "連接失敗!", 1).show();
- return false;
- }
- Toast.makeText(this.context, this.device.getName() + "連接成功!",
- Toast.LENGTH_SHORT).show();
- return true;
- } else {
- return true;
- }
- }
- /**
- * 斷開藍牙設備連接
- */
- public static void disconnect() {
- System.out.println("斷開藍牙設備連接");
- try {
- bluetoothSocket.close();
- outputStream.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- /**
- * 選擇指令
- */
- public void selectCommand() {
- new AlertDialog.Builder(context).setTitle("請選擇指令")
- .setItems(items, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- try {
- outputStream.write(byteCommands[which]);
- } catch (IOException e) {
- Toast.makeText(context, "設置指令失敗!",
- Toast.LENGTH_SHORT).show();
- }
- }
- }).create().show();
- }
- /**
- * 發送數據
- */
- public void send(String sendData) {
- if (this.isConnection) {
- System.out.println("開始打印!!");
- try {
- byte[] data = sendData.getBytes("gbk");
- outputStream.write(data, 0, data.length);
- outputStream.flush();
- } catch (IOException e) {
- Toast.makeText(this.context, "發送失敗!", Toast.LENGTH_SHORT)
- .show();
- }
- } else {
- Toast.makeText(this.context, "設備未連接,請重新連接!", Toast.LENGTH_SHORT)
- .show();
- }
- }
- }</span>








對了對了,差點忘記一件很重要的事情!!清單文件忘記給權限啦!!
權限
- <span style="font-size:14px"><uses-permission android:name="android.permission.BLUETOOTH" />
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> </span>
注冊Activity
- <span style="font-size:14px"><activity android:name=".BluetoothActivity" />
- <activity android:name=".PrintDataActivity" /> </span><span style="font-size:14px">
- </span>

- 下一篇:java實現約瑟夫問題
- 頂
- 5
- 踩
- 0
- 11樓 zywxsg0612 4天前 15:42發表 [回復]
-
-
LZ 你好 問個問題createRfcommSocketToServiceRecord(uuid)
對於其中的UUID,我直接用生成器生成一個復制過去,在這里是可以用的嗎?
還是說uuid有什么特殊的??百度了下 貌似這個識別碼生成后就可以用了。。
還有就是后邊的打印指令
0x1b, 0x40
1b應該是esc 40是@ ??
剛開始學着寫android 很多不是很懂,有些問題 類似USB 啊 打印機 搜出來的都是各種廣告,很少和開發有關。。。
- Re: reality_jie 4天前 16:25發表 [回復]
-
- 回復zywxsg0612:uuid沒有特殊的,直接用生成器生成一個復制過去可以
- Re: zywxsg0612 前天 09:59發表 [回復]
-
- 回復reality_jie:謝謝。。。
- 9樓 qq624196743 2013-11-29 17:52發表 [回復]
-
- 碉堡了,好文啊
- Re: reality_jie 2013-11-29 18:09發表 [回復]
-
- 回復qq624196743:謝謝^_^o~ 努力!
- 8樓 csaily504768527 2013-11-29 11:07發表 [回復]
-
- 樓主你好。我想請問一下,你的那些打印指令還有么。使用你上面的代碼打印中文時候會出現亂碼。。
- Re: reality_jie 2013-11-29 11:10發表 [回復]
-
-
回復csaily504768527:指令就這些。。但是我在我這里的幾台打印機測試都不會出現亂碼哦,如果出現亂碼,你嘗試在里邊修改一下
byte[] data = sendData.getBytes("gbk"): 把gbk修改成utf-8
- Re: csaily504768527 2013-11-29 11:33發表 [回復]
-
- 回復reality_jie:樓主。。還是不成功。。我測試的設備是HP 100 便攜式藍牙打印機。。還嘗試了。。GB2312 .. BIG5... GBK 。等。都還是亂碼。。這怎么搞起。。 好不科學啊。。-_-.......淚崩的節奏中。。
- Re: reality_jie 2013-11-29 14:16發表 [回復]
-
- 回復csaily504768527:出現亂碼的根本原因是打印機和手機發送的數據的編碼不統一。你先去確認一下你的打印機是用什么編碼來表示中文的
- 7樓 蝸蝸牛快跑 2013-11-27 20:32發表 [回復]
-
- 樓主,您好,我最近也想實現一個藍牙打印的功能。但是在藍牙通信的時候遇到了點問題,我的socket在connet這步,一直報錯:java.io.IOException: Service discovery failed。我用的UUID跟你是一樣的,我目前是想連接其他手機(已開啟藍牙服務)。您知道怎么解決么?
- Re: reality_jie 2013-11-27 21:12發表 [回復]
-
- 回復superbinbin1:這個代碼只能用於手機與打印機之間的連接哦
- Re: 蝸蝸牛快跑 2013-11-27 23:15發表 [回復]
-
- 回復reality_jie:這樣呀,那手機之間連接。。。用什么UUID?UUID的類型不是根據服務來選的么?因為我很好奇,安卓自帶的藍牙分享功能,幾乎是無論對方是什么藍牙,都可以把文件分享過去,手機之間自然不用說,電腦端的藍牙適配器也可以傳,hp的打印機我也有試過,可以直接發圖片過去打印。那么他是如何設計的???樓主大神幫忙解答疑惑呀,感激不盡。
- Re: reality_jie 2013-11-29 18:11發表 [回復]
-
- 回復superbinbin1:親,這個問題我也有待研究哦
- Re: reality_jie 2013-11-07 14:40發表 [回復]
-
- 回復feng52101:可以
- 5樓 bhald6821935 2013-10-18 11:20發表 [回復]
-
- 樓主 能發個源碼麼。謝謝646965572@qq.com
- Re: reality_jie 2013-10-18 13:42發表 [回復]
-
-
回復bhald6821935:http://download.csdn.net/detail/reality_jie/6418413
完整源碼
- 4樓 wang158210867 2013-10-12 16:01發表 [回復]
-
- 有沒有遇到 打不了中文 或者 中文亂碼問題呀
- Re: csaily504768527 2013-11-29 11:37發表 [回復]
-
- 回復wang158210867:哥們,你那個亂碼問題找到解決辦法木有。。或者是思路。。
- Re: reality_jie 2013-10-12 17:25發表 [回復]
-
- 回復wang158210867:我自己做的測試都沒有出現中文亂碼哦
- 3樓 zhafei1311 2013-09-27 15:50發表 [回復]
-
- 有沒有打印圖片的代碼
- Re: reality_jie 2013-09-27 17:38發表 [回復]
-
- 回復u012243481:暫時沒有
- 2樓 紅姬茄子 2013-09-25 14:45發表 [回復]
-
- 樓主,我想問下這個android手機連接藍牙打印能不能指定文件打印呢,譬如說我指定一張圖片,或一個文檔什么的讓打印機打印,這種功能能否實現嘞,求指教,嘿嘿
- Re: reality_jie 2013-09-25 17:08發表 [回復]
-
-
public void send(String sendData) {
if (this.isConnection) {
System.out.println("開始打印!!");
try {
byte[] data = sendData.getBytes("gbk");
outputStream.write(data, 0, data.length);
outputStream.flush();
} catch (IOException e) {
Toast.makeText(this.context, "發送失敗!", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(this.context, "設備未連接,請重新連接!", Toast.LENGTH_SHORT)
.show();
}
從這個打印方法可以看出,打印的數據是以二進制流發送出去的。也就是說,如果你想打印外部文檔,只要用一個輸入流,比如BufferedReader把數據讀入再轉成二進制流交給outputStream,應該是能實現的。至於圖片。。。暫時我就不知道怎么弄了
- Re: reality_jie 2013-09-24 17:31發表 [回復]
-
- Y(^_^)Y
核心技術類目
-
閱讀排行
- 安卓手機連接藍牙打印機實現打印功能(958)
- android通過服務實現消息推送(363)
- android加載大圖片到內存(304)
- android從圖庫(gallery)選擇一張圖片(299)
- 安卓短信發送器(247)
- oracle變異表觸發器中ORA-04091錯誤原因及解決方案(243)
- android.view.ViewRootImpl$CalledFromWrongThreadException異常處理(231)
- java多線程同步:生產者與消費者問題(203)
- android+lucene實現全文檢索並高亮關鍵字(192)
- andorid使用異步http框架和第三方HttpClinet上傳文件(171)
-
評論排行
- 安卓手機連接藍牙打印機實現打印功能(28)
- android加載大圖片到內存(1)
- android從圖庫(gallery)選擇一張圖片(0)
- android通過服務實現消息推送(0)
- 安卓短信發送器(0)
- java多線程同步:生產者與消費者問題(0)
- andorid使用異步http框架和第三方HttpClinet上傳文件(0)
- android.view.ViewRootImpl$CalledFromWrongThreadException異常處理(0)
- android.os.NetworkOnMainThreadException異常處理(0)
- adb server is out of date. killing解決方案(0)
-
推薦文章
-
最新評論
- 安卓手機連接藍牙打印機實現打印功能
泓豆奶茶: 按你說的還是成功不了,能加QQ聊嗎?qq:1584166172
- 安卓手機連接藍牙打印機實現打印功能
zywxsg0612: @reality_jie:謝謝。。。
- 安卓手機連接藍牙打印機實現打印功能
reality_jie: @zywxsg0612:uuid沒有特殊的,直接用生成器生成一個復制過去可以
- 安卓手機連接藍牙打印機實現打印功能
zywxsg0612: LZ 你好 問個問題createRfcommSocketToServiceRecord(uuid)對...
- 安卓手機連接藍牙打印機實現打印功能
xingzjx: 謝謝樓主分享!!!
- 安卓手機連接藍牙打印機實現打印功能
reality_jie: @superbinbin1:親,這個問題我也有待研究哦
- 安卓手機連接藍牙打印機實現打印功能
reality_jie: @qq624196743:謝謝^_^o~ 努力!
- 安卓手機連接藍牙打印機實現打印功能
qq624196743: 碉堡了,好文啊
- 安卓手機連接藍牙打印機實現打印功能
reality_jie: @csaily504768527:出現亂碼的根本原因是打印機和手機發送的數據的編碼不統一。你先去確認...
- 安卓手機連接藍牙打印機實現打印功能
csaily504768527: @wang158210867:哥們,你那個亂碼問題找到解決辦法木有。。或者是思路。。
