SoFunction
Updated on 2025-04-08

An example code for Android phone connecting to Jiabo printer via Bluetooth

The printer I use is Jiabo printer, which supports Bluetooth, Wi-Fi, and USB. I use Bluetooth to connect.

I found a source code for Android-developed App on the Internet, but I didn't understand the various jumps, so I asked the Douniang again and found a good article

Android only supports Bluetooth development from 2.0 version of SDK, and the emulator does not support it. At least two mobile phones are required for testing, so it restricts the development of many technicians.

1. First,To operate Bluetooth, you must first add permissions in it

// Permissions to manage Bluetooth devices<uses-permissionandroid:name=".BLUETOOTH_ADMIN" />
// Permissions to use Bluetooth devices<uses-permissionandroid:name="" />

2. Turn on Bluetooth

Get the Bluetooth adapter(), check if the device supports Bluetooth, and if so, turn on Bluetooth.

// Check whether the device supports Bluetoothadapter = (); 
if (adapter == null) 
{ 
// The device does not support Bluetooth} 
// Turn on Bluetoothif (!()) 
{ 
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
// Set Bluetooth visibility, up to 300 seconds(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
(intent); 
}

3. Get the paired Bluetooth device ()

When connecting to a Bluetooth device for the first time, you need to pair it first. Once the pairing is successful, the information of the device will be saved. There is no need to pair it when connecting in the future, so the paired device may not be able to connect.

BluetoothAdapter adapter = (); 
Set<BluetoothDevice> devices = (); 
for(int i=0; i<(); i++) 
{ 
BluetoothDevice device =
BluetoothDevice)().next(); 
(()); 
} 

4. Search for surrounding Bluetooth devices

After the adapter searches for the Bluetooth device, the result will be transmitted in the form of broadcast, so you need to customize a class that inherits the broadcast and obtain and process the search results of the Bluetooth device in the onReceive method.

// Set up broadcast information filteringIntentFilter intentFilter = new IntentFilter(); 
(BluetoothDevice.ACTION_FOUND); 
(BluetoothDevice.ACTION_BOND_STATE_CHANGED); 
(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); 
(BluetoothAdapter.ACTION_STATE_CHANGED); 
// Register a broadcast receiver, receive and process search results(receiver, intentFilter); 
// Looking for Bluetooth devices, and Android will send the found devices in a broadcast form(); 
Custom broadcast class
private BroadcastReceiver receiver = new BroadcastReceiver() { 
@Override 
public void onReceive(Context context, Intent intent) { 
String action = (); 
if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
BluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE); 
(()); 
} 
} 
}

5. Pairing and status monitoring of Bluetooth devices

private BroadcastReceiver receiver = new BroadcastReceiver() { 
@Override 
public void onReceive(Context context, Intent intent) { 
String action = (); 
if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
// Get the found Bluetooth deviceBluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE); 
(()); 
// If the found device matches the device to be connected, processif (().equalsIgnoreCase(name)) { 
// The process of searching for Bluetooth devices takes up a lot of resources. Once you find the device you need to connect to, you need to close the search in time.(); 
// Get the connection status of the Bluetooth deviceconnectState = (); 
switch (connectState) { 
// Not pairedcase BluetoothDevice.BOND_NONE: 
// Pairingtry { 
Method createBondMethod = ("createBond"); 
(device); 
} catch (Exception e) { 
(); 
} 
break; 
// Pairedcase BluetoothDevice.BOND_BONDED: 
try { 
// connectconnect(device); 
} catch (IOException e) { 
(); 
} 
break; 
} 
} 
} else if(BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { 
// State-changed broadcastBluetoothDevice device = (BluetoothDevice.EXTRA_DEVICE); 
if (().equalsIgnoreCase(name)) { 
connectState = (); 
switch (connectState) { 
case BluetoothDevice.BOND_NONE: 
break; 
case BluetoothDevice.BOND_BONDING: 
break; 
case BluetoothDevice.BOND_BONDED: 
try { 
// connectconnect(device); 
} catch (IOException e) { 
(); 
} 
break; 
} 
} 
} 
} 
}

6. Connection of Bluetooth devices

private void connect(BluetoothDevice device) throws IOException { 
// Fixed UUIDfinal String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; 
UUID uuid = (SPP_UUID); 
BluetoothSocket socket = (uuid); 
(); 
} 
private void connect(BluetoothDevice device) throws IOException { 
// Fixed UUIDfinal String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; 
UUID uuid = (SPP_UUID); 
BluetoothSocket socket = (uuid); 
(); 
}

As the name implies, Bluetooth adapter must be operated continuously until we establish a bluetoothSocket connection.

There are many methods in BluetoothAdapter, and the following are commonly used:

cancelDiscovery() literally means canceling discovery, which means that when we are searching for the device, we will no longer continue searching

disable() turns off Bluetooth

enable() to turn on Bluetooth. This method will not pop up the prompt when turning on Bluetooth. More often we need to ask the user whether it is turned on. These two lines of code also turn on Bluetooth, but will prompt the user:

Intemtenabler=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(enabler,reCode);//Same as startActivity(enabler);

getAddress() gets the local Bluetooth address

getDefaultAdapter() gets the default BluetoothAdapter. In fact, there is only one method to get BluetoothAdapter.

getName() gets the local Bluetooth name

getRemoteDevice(String address) Obtain remote Bluetooth device based on Bluetooth address

getState() gets the current status of the local Bluetooth adapter (it feels that it may be more needed when debugging)

isDiscovering() determines whether the device is currently being searched, and returns true

isEnabled() determines whether Bluetooth is turned on. Return true if it is turned on. Otherwise, return false

listenUsingRfcommWithServiceRecord(String name,UUID uuid) Create and return BluetoothServerSocket according to the name, UUID, which is the first step in creating a BluetoothSocket server side.

startDiscovery() starts searching, this is the first step in searching

You can tell by the name that this class describes a Bluetooth device

createRfcommSocketToServiceRecord(UUIDuuid) creates according to UUID and returns a BluetoothSocket

This method is also the purpose of our acquisition of BluetoothDevice - to create a BluetoothSocket

Other methods of this class, such as getAddress(), getName(), and BluetoothAdapter

If Bluetooth is removed, I believe everyone will be familiar with it. Since it is a Socket, the methods should be similar.

There are only three methods for this class

The difference between the two overloaded accept() and accept(inttimeout) is that the subsequent method specifies the outdated time. It should be noted that when these two methods are executed, the thread will be blocked until the client's request is received (or after it expires), and it should be run in the new thread!

Another thing to note is that both methods return a BluetoothSocket, and the final connection is also the connection between the server and the client.

Needless to say, close(), translate it - close!

, opposite to BluetoothServerSocket, is the client

There are 5 methods in total, and if nothing unexpected happens, you will use them

close(), close()

connect() connection

getInptuStream() gets the input stream

getOutputStream() gets the output stream

getRemoteDevice() gets the remote device, which refers to the remote Bluetooth device specified to obtain the bluetoothSocket connection.

According to this article, I just changed the last Bluetooth connection part (because Jiabo printer has its own SDK and the SDK has its own connection method) and import the downloaded DEMO and xUtils-2.6. packages. The subsequent connection method is as follows:

/**
 *connect
 */
private voidconnect() {
intrel =0;
try{//Use port 1, 4 means that the mode is Bluetooth mode, Bluetooth address, and the default is 0 in the endrel = (1,4,(loction),0);
}catch(RemoteException e) {
();
}
GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
if(r != GpCom.ERROR_CODE.SUCCESS) {
if(r == GpCom.ERROR_CODE.DEVICE_ALREADY_OPEN) {
//Open successfully}else{
((r));
}
}else{
();
("fail");
}
}

Don’t forget that mGpService is a service of Jiabo SDK. You must first obtain it and bind it to the Activity;

protected voidonCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_buletooth);
connection();
}
private voidconnection() {
conn=newPrinterServiceConnection();
Intent intent =newIntent(this, );
(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= (service);
}
}

You also need to configure the service in the manifest file

<service
android:name=""
android:enabled="true"
android:exported="true"
android:label="GpPrintService">
<intent-filter>
<actionandroid:name=""/>
</intent-filter>
</service>
<serviceandroid:name="">
</service>

After doing these, I was done and I could connect to the printer, but I still couldn't print. I also had to make some printing configurations. Due to my project, the connection and printing were not on the same interface, so I continued to study Jiabo source code and found that if the previous link was successful, I only need one configuration in another interface and print it directly. The code is as follows:

public {
@Bind(.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) {
(msg);
}
};
}
privateBroadcastReceivermBroadcastReceiver=newBroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = ();
("TAG", action);
// GpCom.ACTION_DEVICE_REAL_STATUS is the broadcast IntentFilterif((GpCom.ACTION_DEVICE_REAL_STATUS)) {
//The request code of business logic, where to query what operations to dointrequestCode = (GpCom.EXTRA_PRINTER_REQUEST_CODE, -1);
//Judge the request code, then perform business operationsif(requestCode ==MAIN_QUERY_PRINTER_STATUS) {
intstatus = (GpCom.EXTRA_PRINTER_REAL_STATUS,16);
String str;
if(status == GpCom.STATE_NO_ERR) {
str ="The printer is normal";
}else{
str ="printer ";
if((byte) (status &amp; GpCom.STATE_OFFLINE) &gt; 0) {
str +="Offline";
}
if((byte) (status &amp; GpCom.STATE_PAPER_ERR) &gt; 0) {
str +="Under paper";
}
if((byte) (status &amp; GpCom.STATE_COVER_OPEN) &gt; 0) {
str +="Print cover";
}
if((byte) (status &amp; GpCom.STATE_ERR_OCCURS) &gt; 0) {
str +="The printer error";
}
if((byte) (status &amp; GpCom.STATE_TIMES_OUT) &gt; 0) {
str +="Query timeout";
}
}
(getApplicationContext(),"printer:"+1+"state:"+ str, Toast.LENGTH_SHORT)
.show();
}else if(requestCode ==REQUEST_PRINT_RECEIPT) {
intstatus = (GpCom.EXTRA_PRINTER_REAL_STATUS,16);
if(status == GpCom.STATE_NO_ERR) {
sendReceipt();
}else{
(,"query printer status error", Toast.LENGTH_SHORT).show();
}
}
}
}
};
@Override
protected void initTitle() {
("Print");
}
private void connection() {
conn=newPrinterServiceConnection();
Intent intent =newIntent(this, );
(intent,conn, Context.BIND_AUTO_CREATE);// bindService
}
classPrinterServiceConnectionimplementsServiceConnection {
@Override
public void onServiceDisconnected(ComponentName name) {
("ServiceConnection","onServiceDisconnected() called");
mGpService=null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mGpService= (service);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_print);
connection();
//Register real-time status query broadcastregisterReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_DEVICE_REAL_STATUS));
/**
 *In ticket mode, you can register the broadcast, add addQueryPrinterStatus() at the end of the content that needs to be printed, and you will receive it after printing.
 * action is broadcast of GpCom.ACTION_DEVICE_STATUS, especially for continuous printing,
 *Refer to the sendReceiptWithResponse method in this sample and the processing in broadcast
 **/
registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_RECEIPT_RESPONSE));
/**
 *In tag mode, you can register the broadcast and add addQueryPrinterStatus(RESPONSE_MODE mode) at the end of the content you need to print.
 *, After printing, the broadcast will be received, the action is GpCom.ACTION_LABEL_RESPONSE, especially for continuous printing.
 *Refer to the sendLabelWithResponse method in the sample and the processing in broadcast
 **/
registerReceiver(mBroadcastReceiver,newIntentFilter(GpCom.ACTION_LABEL_RESPONSE));
}
@Override
protected void initView() {
(this);
}
@Override
public void onClick(View v) {
switch(()) {
.print_print:
if(mGpService==null) {
("Service is on");
}else{
try{
inttype =(1);
if(type == GpCom.ESC_COMMAND) {
(1,1000,REQUEST_PRINT_RECEIPT);
}else{
(this,"Printer is not receipt mode", Toast.LENGTH_SHORT).show();
}
}catch(RemoteException e1) {
();
}
}
break;
}
}
private void sendReceipt() {
EscCommand esc =newEscCommand();
();
((byte)3);
();//Set print center(, , , , );//Set to double height and width("asdfkldsjgfsdl\n");//Print text();
/*Print text */
(, , , , );//Cancel the height and width();//Set the print left alignment("dfkdsgklfds\n");//Print text// ("Welcome to use SMARNET printer!\n"); //Print text// /*Print traditional Chinese requires the printer to support traditional Chinese font library */
// String message = "Jiabo Zhiqian Certificate Printer\n";// // (message,"BIG5");
// (message, "GB2312");
();
/*Please check the GP58 programming manual for details */
("Product Name");
((byte)7, (byte)0);
((short)6);
("Order number");
((short)10);
("state");
();
("apple");
((byte)7, (byte)0);
((short)6);
("12345");
((short)10);
("normal");
();
("Fruit Orange 300ml");
((byte)7, (byte)0);
((short)6);
("3545456");
((short)10);
("normal");
();
// /*Print pictures */
// ("Print bitmap!\n"); //Print text// Bitmap b = (getResources(), );
// (b, 384, 0); //Print picture// /*Print one-dimensional barcode */
// ("Print code128\n"); //Print text// (EscCommand.HRI_POSITION.BELOW);//
// // Set the barcode to recognize the character position below the barcode// ((byte) 60); //Set the barcode height to 60 points// ((byte) 1); //Set the barcode unit width to 1// esc.addCODE128(("SMARNET")); //Print Code128// ();
/*
 * QRCode command printing This command can only be used on models that support QRCode command printing.  On models that do not support QR code printing, you need to send a QR barcode picture
 */
("Merchant QR Code\n");//Print text((byte)0x31);//Set error correction level((byte)6);//Set the qrcode module size("dfgdgs");//Set qrcode content();//Print QRCode();
/*Print text */();//Set the print left alignment("Completed!\r\n");//Print end//Open the money box(.F5, (byte)255, (byte)255);
((byte)8);
Vector&lt;Byte&gt; datas = ();//Send databyte[] bytes = GpUtils.ByteTo_byte(datas);
String sss = (bytes, );
intrs;
try{
rs =(1, sss);
GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rs];
if(r != GpCom.ERROR_CODE.SUCCESS) {
(getApplicationContext(), (r), Toast.LENGTH_SHORT).show();
}
}catch(RemoteException e) {
//TODO Auto-generated catch block
();
}
}
}

It's done, and I feel so good after printing it

The above is the example code for Android phones connected to Jiabo printer via Bluetooth that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!