// 管理蓝牙设备的权限 <uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN" /> // 使用蓝牙设备的权限 <uses-permissionandroid:name="android.permission.BLUETOOTH" />
// 检查设备是否支持蓝牙
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null)
{
// 设备不支持蓝牙
}
// 打开蓝牙
if (!adapter.isEnabled())
{
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 设置蓝牙可见性,最多300秒
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
context.startActivity(intent);
}
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> devices = adapter.getBondedDevices();
for(int i=0; i<devices.size(); i++)
{
BluetoothDevice device =
BluetoothDevice)devices.iterator().next();
System.out.println(device.getName());
}
// 设置广播信息过滤
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
// 注册广播接收器,接收并处理搜索结果
context.registerReceiver(receiver, intentFilter);
// 寻找蓝牙设备,android会将查找到的设备以广播形式发出去
adapter.startDiscovery();
自定义广播类
private BroadcastReceiver receiver = new BroadcastReceiver() {
@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);
System.out.println(device.getName());
}
}
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@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);
System.out.println(device.getName());
// 如果查找到的设备符合要连接的设备,处理
if (device.getName().equalsIgnoreCase(name)) {
// 搜索蓝牙设备的过程占用资源比较多,一旦找到需要连接的设备后需要及时关闭搜索
adapter.cancelDiscovery();
// 获取蓝牙设备的连接状态
connectState = device.getBondState();
switch (connectState) {
// 未配对
case BluetoothDevice.BOND_NONE:
// 配对
try {
Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
createBondMethod.invoke(device);
} catch (Exception e) {
e.printStackTrace();
}
break;
// 已配对
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
// 状态改变的广播
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName().equalsIgnoreCase(name)) {
connectState = device.getBondState();
switch (connectState) {
case BluetoothDevice.BOND_NONE:
break;
case BluetoothDevice.BOND_BONDING:
break;
case BluetoothDevice.BOND_BONDED:
try {
// 连接
connect(device);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
}
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}
private void connect(BluetoothDevice device) throws IOException {
// 固定的UUID
final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
UUID uuid = UUID.fromString(SPP_UUID);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
}
/**
*连接
*/
private voidconnect() {
intrel =0;
try{//使用端口1,4代表模式为蓝牙模式,蓝牙地址,最后默认为0
rel = mGpService.openPort(1,4,adressData.get(loction),0);
}catch(RemoteException e) {
e.printStackTrace();
}
GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
if(r != GpCom.ERROR_CODE.SUCCESS) {
if(r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
//开启成功
}else{
UIUtils.showMessage(GpCom.getErrorText(r));
}
}else{
ProgressDialogUtil.dismiss(BuleToothActivity.this);
UIUtils.showMessage("失败");
}
}
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buletooth);
connection();
}
private voidconnection() {
conn=newPrinterServiceConnection();
Intent intent =newIntent(this, GpPrintService.class);
this.bindService(intent,conn, Context.BIND_AUTO_CREATE);// bindService
}
classPrinterServiceConnectionimplementsServiceConnection {
@Override
public void onServiceDisconnected(ComponentName name) {
mGpService=null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mGpService= GpService.Stub.asInterface(service);
}
}
<service android:name="com.gprinter.service.GpPrintService" android:enabled="true" android:exported="true" android:label="GpPrintService"> <intent-filter> <actionandroid:name="com.gprinter.aidl.GpPrintService"/> </intent-filter> </service> <serviceandroid:name="com.gprinter.service.AllService"> </service>
public classPrintActivityextendsBaseActivityimplementsView.OnClickListener{
@Bind(R.id.print_print)
Buttonprint;
privateGpServicemGpService=null;
privatePrinterServiceConnectionconn=null;
private static final int MAIN_QUERY_PRINTER_STATUS=0xfe;
private static final int REQUEST_PRINT_LABEL=0xfd;
private static final int REQUEST_PRINT_RECEIPT=0xfc;
private int mTotalCopies=0;
@Override
protected void initHandler() {
handler=newHandler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
}
};
}
privateBroadcastReceivermBroadcastReceiver=newBroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d("TAG", action);
// GpCom.ACTION_DEVICE_REAL_STATUS 为广播的IntentFilter
if(action.equals(GpCom.ACTION_DEVICE_REAL_STATUS)) {
//业务逻辑的请求码,对应哪里查询做什么操作
intrequestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1);
//判断请求码,是则进行业务操作
if(requestCode ==MAIN_QUERY_PRINTER_STATUS) {
intstatus = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS,16);
String str;
if(status == GpCom.STATE_NO_ERR) {
str ="打印机正常";
}else{
str ="打印机 ";
if((byte) (status & GpCom.STATE_OFFLINE) > 0) {
str +="脱机";
}
if((byte) (status & GpCom.STATE_PAPER_ERR) > 0) {
str +="缺纸";
}
if((byte) (status & GpCom.STATE_COVER_OPEN) > 0) {
str +="打印机开盖";
}
if((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) {
str +="打印机出错";
}
if((byte) (status & GpCom.STATE_TIMES_OUT) > 0) {
str +="查询超时";
}
}
Toast.makeText(getApplicationContext(),"打印机:"+1+"状态:"+ str, Toast.LENGTH_SHORT)
.show();
}else if(requestCode ==REQUEST_PRINT_RECEIPT) {
intstatus = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS,16);
if(status == GpCom.STATE_NO_ERR) {
sendReceipt();
}else{
Toast.makeText(PrintActivity.this,"query printer status error", Toast.LENGTH_SHORT).show();
}
}
}
}
};
@Override
protected void initTitle() {
mTitleTextMiddle.setText("打印");
}
private void connection() {
conn=newPrinterServiceConnection();
Intent intent =newIntent(this, GpPrintService.class);
this.bindService(intent,conn, Context.BIND_AUTO_CREATE);// bindService
}
classPrinterServiceConnectionimplementsServiceConnection {
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("ServiceConnection","onServiceDisconnected() called");
mGpService=null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mGpService= GpService.Stub.asInterface(service);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print);
connection();
//注册实时状态查询广播
registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_DEVICE_REAL_STATUS));
/**
*票据模式下,可注册该广播,在需要打印内容的最后加入addQueryPrinterStatus(),在打印完成后会接收到
* action为GpCom.ACTION_DEVICE_STATUS的广播,特别用于连续打印,
*可参照该sample中的sendReceiptWithResponse方法与广播中的处理
**/
registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_RECEIPT_RESPONSE));
/**
*标签模式下,可注册该广播,在需要打印内容的最后加入addQueryPrinterStatus(RESPONSE_MODE mode)
*,在打印完成后会接收到,action为GpCom.ACTION_LABEL_RESPONSE的广播,特别用于连续打印,
*可参照该sample中的sendLabelWithResponse方法与广播中的处理
**/
registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_LABEL_RESPONSE));
}
@Override
protected void initView() {
print.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
caseR.id.print_print:
if(mGpService==null) {
UIUtils.showMessage("服务正在开启");
}else{
try{
inttype =mGpService.getPrinterCommandType(1);
if(type == GpCom.ESC_COMMAND) {
mGpService.queryPrinterStatus(1,1000,REQUEST_PRINT_RECEIPT);
}else{
Toast.makeText(this,"Printer is not receipt mode", Toast.LENGTH_SHORT).show();
}
}catch(RemoteException e1) {
e1.printStackTrace();
}
}
break;
}
}
private void sendReceipt() {
EscCommand esc =newEscCommand();
esc.addInitializePrinter();
esc.addPrintAndFeedLines((byte)3);
esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印居中
esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);//设置为倍高倍宽
esc.addText("asdfkldsjgfsdl\n");//打印文字
esc.addPrintAndLineFeed();
/*打印文字 */
esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍宽
esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐
esc.addText("dfkdsgklfds\n");//打印文字
// esc.addText("Welcome to use SMARNET printer!\n"); //打印文字
// /*打印繁体中文需要打印机支持繁体字库 */
// String message = "佳博智匯票據打印機\n";
// // esc.addText(message,"BIG5");
// esc.addText(message, "GB2312");
esc.addPrintAndLineFeed();
/*绝对位置具体详细信息请查看GP58编程手册 */
esc.addText("商品名称");
esc.addSetHorAndVerMotionUnits((byte)7, (byte)0);
esc.addSetAbsolutePrintPosition((short)6);
esc.addText("订单号");
esc.addSetAbsolutePrintPosition((short)10);
esc.addText("状态");
esc.addPrintAndLineFeed();
esc.addText("苹果");
esc.addSetHorAndVerMotionUnits((byte)7, (byte)0);
esc.addSetAbsolutePrintPosition((short)6);
esc.addText("12345");
esc.addSetAbsolutePrintPosition((short)10);
esc.addText("正常");
esc.addPrintAndLineFeed();
esc.addText("果粒橙300ml");
esc.addSetHorAndVerMotionUnits((byte)7, (byte)0);
esc.addSetAbsolutePrintPosition((short)6);
esc.addText("3545456");
esc.addSetAbsolutePrintPosition((short)10);
esc.addText("正常");
esc.addPrintAndLineFeed();
// /*打印图片 */
// esc.addText("Print bitmap!\n"); //打印文字
// Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.gprinter);
// esc.addRastBitImage(b, 384, 0); //打印图片
// /*打印一维条码 */
// esc.addText("Print code128\n"); //打印文字
// esc.addSelectPrintingPositionForHRICharacters(EscCommand.HRI_POSITION.BELOW);//
// //设置条码可识别字符位置在条码下方
// esc.addSetBarcodeHeight((byte) 60); //设置条码高度为60点
// esc.addSetBarcodeWidth((byte) 1); //设置条码单元宽度为1
// esc.addCODE128(esc.genCodeB("SMARNET")); //打印Code128码
// esc.addPrintAndLineFeed();
/*
* QRCode命令打印此命令只在支持QRCode命令打印的机型才能使用。在不支持二维码指令打印的机型上,则需要发送二维条码图片
*/
esc.addText("商家二维码\n");//打印文字
esc.addSelectErrorCorrectionLevelForQRCode((byte)0x31);//设置纠错等级
esc.addSelectSizeOfModuleForQRCode((byte)6);//设置qrcode模块大小
esc.addStoreQRCodeData("dfgdgs");//设置qrcode内容
esc.addPrintQRCode();//打印QRCode
esc.addPrintAndLineFeed();
/*打印文字 */esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印左对齐
esc.addText("Completed!\r\n");//打印结束
//开钱箱
esc.addGeneratePlus(LabelCommand.FOOT.F5, (byte)255, (byte)255);
esc.addPrintAndFeedLines((byte)8);
Vector<Byte> datas = esc.getCommand();//发送数据
byte[] bytes = GpUtils.ByteTo_byte(datas);
String sss = Base64.encodeToString(bytes, Base64.DEFAULT);
intrs;
try{
rs =mGpService.sendEscCommand(1, sss);
GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rs];
if(r != GpCom.ERROR_CODE.SUCCESS) {
Toast.makeText(getApplicationContext(), GpCom.getErrorText(r), Toast.LENGTH_SHORT).show();
}
}catch(RemoteException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有