您的位置:首页 > 移动开发 > Android开发

android 蓝牙打印

2016-12-08 13:34 351 查看
第一步 判断蓝牙是否打开

用到的方法:

/*
* 查询蓝牙
*/
public boolean isOpen() {
return this.bluetoothAdapter.isEnabled();
}


第二步 打开或关闭蓝牙

/**
* 开启蓝牙
*/
public void openBluetooth(Activity activity) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, 1);

}


第三步 搜索蓝牙设备
/**
* 搜索蓝牙设备
*/

public void searchDevices() {
this.bondDevices.clear();
this.unbondDevices.clear();

// 寻找蓝牙设备,android会将查找到的设备以广播的形式发出去
this.bluetoothAdapter.startDiscovery();

}


第四步 连接蓝牙设备

接下来我们来看一下蓝牙工具类

我已经了注释

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.toocms.frame.ui.BaseActivity;
import com.txunda.zbptsj.R;
import com.txunda.zbptsj.activity.PrintDataService;
import com.txunda.zbptsj.activity.SetBluetoothAty;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothService {

private Context context;

private ListView unbondDevicesListView;
private ListView bondDevicesListView;
private TextView searchDevice;
/**
* 获得本设备蓝牙设备器的实列
*/
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

private PrintDataService printDataService = null;
private ProgressDialog dialog;
/**
* 存放蓝牙设备
*
* 1:存放未配对的蓝牙设备
*
* 2:存放已配对的蓝牙设备
*/
private ArrayList<BluetoothDevice> unbondDevices = null;
private ArrayList<BluetoothDevice> bondDevices = null;

private boolean flag;

/**
* 添加已绑定蓝牙设备到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中
}
System.out.println("+++++++++++++++++data:" + bondDevices);
//
String[] from = { "deviceName" };
int[] to = { R.id.device_name };
SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data, R.layout.bonddevice_item, from, to);
// 把适配器装载到listView中
this.unbondDevicesListView.setAdapter(simpleAdapter);

this.unbondDevicesListView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
final BluetoothDevice device = bondDevices.get(arg2);
printDataService = new PrintDataService(context, device.getAddress());
// dialog = ProgressDialog.show(context, null, "正在连接蓝牙中...",
// true, false);
/**
* 连接蓝牙
*/
initView(device.getAddress());

}
});

}

private void initView(String deviceAddress) {
// 一上来就先连接蓝牙设备
flag = printDataService.connect();

if (flag == false) {
// dialog.dismiss();
// 连接失败
Toast.makeText(context, "连接失败", Toast.LENGTH_SHORT).show();
} else {
// 连接成功
Toast.makeText(context, "连接成功!", Toast.LENGTH_SHORT).show();
// dialog.dismiss();
SharedPloginUtils.putValue(context, "deviceAddress_key", deviceAddress);
((Activity) context).finish();

}

}

/**
* 添加未绑定蓝牙设备到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.undevice_name };
SimpleAdapter simpleAdapter = new SimpleAdapter(this.context, data, R.layout.unbonddevice_item, from, to);

// 把适配器装载到listView中
this.bondDevicesListView.setAdapter(simpleAdapter);

// 为每个item绑定监听,用于设备间的配对
this.bondDevicesListView.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() {

}

/**
* 第一步:需要给BluetoothService以下几个参数:
*
* 1:context
*
* 2:unbondDevicesListView 未连接的ListView
*
* 3:bondDevicesListView 连接的ListViews
*
* 4:button_scan:搜索按钮
*
* @param context
* @param unbondDevicesListView
* @param bondDevicesListView
* @param button_scan
*/

public BluetoothService(Context context, ListView unbondDevicesListView, ListView bondDevicesListView,
TextView button_scan) {
this.context = context;
this.unbondDevicesListView = unbondDevicesListView;
this.bondDevicesListView = bondDevicesListView;
this.searchDevice = button_scan;

/**
*存放搜索到的数据
*
*unbondDevices:未连接的
*
*bondDevices:已连接的
*
*
*/

unbondDevices = new ArrayList<BluetoothDevice>();
bondDevices = new ArrayList<BluetoothDevice>();

/**
* 获取已连接的设备
*
* 把已连接的设备保存到bondDevices
*/
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
Object o = it.next();
this.bondDevices.add((BluetoothDevice) o);
}
//调用addBondDevicesToListView()方法初始化
addBondDevicesToListView();
//注册广播
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();
}

/*
* 查询蓝牙
*/
public boolean isOpen() {
return this.bluetoothAdapter.isEnabled();
}

/**
* 搜索蓝牙设备
*/
public void searchDevices() {
this.bondDevices.clear();
this.unbondDevices.clear();

// 寻找蓝牙设备,android会将查找到的设备以广播的形式发出去
this.bluetoothAdapter.startDiscovery();

}

/**
* addUnbondDevices 添加未绑定的蓝牙设备到ListView
*/
private void addUnbondDevices(BluetoothDevice device) {
// TODO Auto-generated method stub
System.out.println("未绑定设备的名称:" + device);
if (!this.unbondDevices.contains(device)) {
this.unbondDevices.add(device);
}
}

/**
* 添加已绑定的设备到ListView
*/
private void addBandDevices(BluetoothDevice device) {
// TODO Auto-generated method stub
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) {
// TODO Auto-generated method stub
/**
* 广播接收的信息
*/
String action = intent.getAction();

/**
* 发现设备的广播
*/
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

/**
* true:已配对的蓝牙设备
*
* false:未配对的蓝牙设备
*/
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
System.out.println("++++已配对的设备:" + device);
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关闭
*
* 添加已绑定蓝牙设备到ListView
*
* 添加未绑定蓝牙设备到ListView
*/
progressDialog.dismiss();
addUnbondDevicesToListView();
addBondDevicesToListView();
// bluetoothAdapter.cancelDiscovery();
}
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
/**
* true:打开蓝牙
*
* false:关闭蓝牙
*/
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
System.out.println("--------打开蓝牙-----------");
searchDevice.setEnabled(true);
bondDevicesListView.setEnabled(true);
unbondDevicesListView.setEnabled(true);
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
System.out.println("--------关闭蓝牙-----------");
searchDevice.setEnabled(false);
bondDevicesListView.setEnabled(false);
unbondDevicesListView.setEnabled(false);
}
}
}
};
}





第五步 打印

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.widget.Toast;

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) {
if (isConnection) {
try {
outputStream.write(byteCommands[which]);

} catch (IOException e) {
Toast.makeText(context, "设置指令失败!",
Toast.LENGTH_SHORT).show();
}
} else {
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();

}
}
}














































                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息