Android phone to connect the example code of the _android printer via Bluetooth

Source: Internet
Author: User
Tags base64 stub uuid

The printer used is a good Bo printer, support Bluetooth, WiFi, USB I am using Bluetooth to connect.

On the internet to find a good Bo official for Android development of the app source code, but a variety of jumps, did not see too understand, so again to ask Niang, found a good article

Android for Bluetooth development from the 2.0 version of the SDK to support, and the simulator does not support the test requires at least two mobile phones, so the development of many technical personnel constraints.

1. First of all, to operate Bluetooth, first in the Androidmanifest.xml to add permissions

Manage permissions for Bluetooth devices 
<uses-permissionandroid:name= "Android.permission.BLUETOOTH_ADMIN"/>
//rights 
to use Bluetooth devices <uses-permissionandroid:name= "Android.permission.BLUETOOTH"/>

2. Turn on Bluetooth

Obtain the Bluetooth adapter (android.bluetooth.BluetoothAdapter), check whether the device supports Bluetooth, and if so, turn on Bluetooth.

Check if the device supports Bluetooth 
adapter = Bluetoothadapter.getdefaultadapter (); 
if (adapter = null) 
{ 
//device does not support Bluetooth 
} 
//Open Bluetooth 
if (!adapter.isenabled ()) 
{ 
Intent Intent = new Intent (bluetoothadapter.action_request_enable); 
Set Bluetooth visibility, up to 300 seconds 
Intent.putextra (bluetoothadapter.extra_discoverable_duration,300);
Context.startactivity (intent); 
}

3. Get the paired Bluetooth device (Android.bluetooth.BluetoothDevice)

First connection to a Bluetooth device needs to be paired first, once the pairing is successful, the device's information will be saved, the subsequent connection no longer need to match, so the paired device is not necessarily able to connect.

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

4. Search the surrounding Bluetooth devices

The adapter searches the Bluetooth device for a broadcast of the results, so you need to customize a class that inherits the broadcast, and then obtain and process the search results for the Bluetooth device in the OnReceive method.

Set Broadcast information filter 
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); 
Registers the broadcast receiver, receives and processes the search result 
context.registerreceiver (receiver, intentfilter); 
Looking for a Bluetooth device, Android will send the found device to the 
Adapter.startdiscovery () in broadcast form; 
Custom broadcast class
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 ());}} 

5. Pairing and status monitoring of Bluetooth devices

Private Broadcastreceiver receiver = new Broadcastreceiver () {@Override public void onreceive (context context, Intent 
Intent) {String action = intent.getaction (); if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {//Get the found Bluetooth device bluetoothdevice device = Intent.getparcelableextra ( 
Bluetoothdevice.extra_device); 
System.out.println (Device.getname ()); 
If a device is found that matches the device to be connected, processing if (Device.getname (). Equalsignorecase (name)) {//Searching for Bluetooth devices takes up more resources, and you need to close the search immediately after you find the device you need to connect to 
Adapter.canceldiscovery (); 
Gets the connection status of the Bluetooth device connectstate = Device.getbondstate (); Switch (connectstate) {//Not paired case Bluetoothdevice.bond_none://Pairing try {method Createbondmethod = Bluetoothdevice. 
Class.getmethod ("Createbond"); 
Createbondmethod.invoke (device); 
catch (Exception e) {e.printstacktrace (); 
} break; 
Matched case BluetoothDevice.BOND_BONDED:try {//connection connect (device); 
catch (IOException e) {e.printstacktrace (); 
} break; }} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equalS (action)) {//state-changed broadcast 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 {//connection connect (device); 
catch (IOException e) {e.printstacktrace (); 
} break; } 
} 
} 
} 
}

6. Bluetooth Device Connection

private void Connect (Bluetoothdevice device) throws IOException { 
//fixed UUID 
final String spp_uuid = "00001101-00 00-1000-8000-00805F9B34FB "; 
UUID uuid = uuid.fromstring (spp_uuid); 
Bluetoothsocket socket = Device.createrfcommsockettoservicerecord (UUID); 
Socket.connect (); 
} 
private void Connect (Bluetoothdevice device) throws IOException { 
//fixed UUID 
final String spp_uuid = "00001101-0 000-1000-8000-00805F9B34FB "; 
UUID uuid = uuid.fromstring (spp_uuid); 
Bluetoothsocket socket = Device.createrfcommsockettoservicerecord (UUID); 
Socket.connect (); 
}

1.BluetoothAdapter as the name suggests, Bluetooth adapter, until we establish bluetoothsocket connection, we must continue to operate it

There are many methods in Bluetoothadapter, commonly used in the following:

Canceldiscovery () by literal means cancels the discovery, which means that when we are searching for the device, calling this method will no longer continue the search

Disable () Turn off Bluetooth

Enable () Turn on Bluetooth, this method turns on Bluetooth will not pop-up prompts, more times we need to ask the user whether to open, and then the two lines of code is also open Bluetooth, but will prompt the user:

Intemtenabler=new Intent (bluetoothadapter.action_request_enable);

Startactivityforresult (Enabler,recode);/with startactivity (enabler);

GetAddress () get local Bluetooth address

Getdefaultadapter () Gets the default Bluetoothadapter, which is actually the only way to get Bluetoothadapter

GetName () get local bluetooth name

Getremotedevice (String address) to obtain a remote Bluetooth device from a Bluetooth location

GetState () Gets the current state of the local Bluetooth adapter (more needed when it feels likely to be debugged)

Isdiscovering () Determines whether the device is currently being looked up, and returns True

IsEnabled () to determine if Bluetooth is turned on, turned on returns True, otherwise, returns false

Listenusingrfcommwithservicerecord (String name,uuid uuid) by name, UUID creates and returns Bluetoothserversocket, This is the first step to creating the Bluetoothsocket server side

StartDiscovery () Start the search, this is the first step of the search

2.BluetoothDevice read the name to know that this class describes a Bluetooth device

Createrfcommsockettoservicerecord (UUIDUUID) creates and returns a bluetoothsocket based on the UUID

This method is also the purpose of our acquisition of Bluetoothdevice--creating Bluetoothsocket

Other methods of this class, such as GetAddress (), GetName (), and Bluetoothadapter

3.BluetoothServerSocket if you go except for Bluetooth I believe that we must be familiar with, since the socket, the method should be similar,

This class has only three methods

Two overloaded accept (), the difference between the Accept (Inttimeout) is that the following method specifies the elapsed time, and it should be noted that when the two methods are executed, the thread is blocked until the client's request is received (or expired) and should be run in a new thread!

It is also important to note that both methods return a bluetoothsocket, and the final connection is the server-side connection to the client's two Bluetoothsocket

Close () This is needless to say, translate it-shut up!

4.BluetoothSocket, relative to Bluetoothserversocket, is the client

A total of 5 methods, no accident, will use

Close (), closing

Connect () connection

Getinptustream () get the input stream

Getoutputstream () Get output stream

Getremotedevice () Gets the remote device, which refers to the remote Bluetooth device that gets the Bluetoothsocket specified connection

This article only changes the last Bluetooth connection section (because the Good Bo printer has its own SDK, The SDK has its own connection method) to import the Gprintersdkv22.jar and Xutils-2.6.14.jar two packages from the downloaded demo, followed by the following connection methods:

/**
* Connection * *
Private voidconnect () {
Intrel =0;
try{//uses the port 1,4 for Bluetooth mode, the Bluetooth address, and the last default is 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) {
//Open successfully
}else{
uiutils.showmessage (Gpcom.geterrortext (R));
}
else{
Progressdialogutil.dismiss (buletoothactivity.this);
Uiutils.showmessage ("failed");
}

Do not forget that Mgpservice is a good Bo SDK's one of their own services, to obtain first, and with the activity to bind;

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

and configure the service in the manifest file.

<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>

After this is done, you can connect to the printer, but still can not print, but also to do some printing configuration, because of my project reasons, connection and printing is not in the same interface, so continue to study the good Bo source code, found that if the previous link has been successful, In another interface just a single configuration can be printed directly with the following code:

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 (msg) {Super.h
Andlemessage (msg);
}
}; } privatebroadcastreceivermbroadcastreceiver=newbroadcastreceiver () {@Override public void onreceive
, Intent Intent) {String action = intent.getaction ();
LOG.D ("TAG", action); Gpcom.action_device_real_status for broadcast Intentfilter if (Action.equals (gpcom.action_device_real_status)) {//Business logic request code
, corresponding to where the query do what operation Intrequestcode = Intent.getintextra (Gpcom.extra_printer_request_code,-1); Determine the request code, is the business operation if (Requestcode ==main_query_printer_status) {intstatus = inteNt.getintextra (gpcom.extra_printer_real_status,16);
String str; if (status = = Gpcom.state_no_err) {str = "printer normal";}
else{str = "printer"; if ((byte) (Status & Gpcom.state_offline) > 0) {str = "offline";} if ((Byte) (Status & Gpcom.state_paper_err) > 0 {str + = "paper Missing";} if ((Byte) (Status & Gpcom.state_cover_open) > 0) {str = "printer open cover";} if ((Byte) (Status & gpcom .
State_err_occurs) > 0) {str = "printer error";} if ((Byte) (Status & Gpcom.state_times_out) > 0) {str + + query timeout;}}
Toast.maketext (Getapplicationcontext (), "Printer:" +1+ "Status:" + 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 ("print");} private void Connection () {Conn=newprinterservi
Ceconnection ();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 ();
Register real-time status query broadcast Registerreceiver (Mbroadcastreceiver,newintentfilter (gpcom.action_device_real_status));
/** * Ticket mode, you can register the broadcast, in the need to print the final add addqueryprinterstatus (), after the completion of the printing will receive the * ACTION for gpcom.action_device_status broadcast, especially for continuous printing, * can refer to the Sendreceiptwithresponse method in this sample and the processing in the broadcast **/Registerreceiver (Mbroadcastreceiver,newintentfilter (
Gpcom.action_receipt_response)); /** * Tag mode, you can register the broadcast, in the need to print the last of the content to join the adDqueryprinterstatus (Response_mode MODE) *, when the print is complete, will receive, ACTION for gpcom.action_label_response broadcast, especially for continuous printing, * Reference to the Sendlabelwithresponse method in this sample and the processing in the broadcast **/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 ("service is Open");} else{try{inttype =mgpservice.getprintercommandtype (1); if (type = = Gpcom.esc_command) {Mgpservice.queryprinterstatus
(1,1000,request_print_receipt); }else{Toast.maketext (This, "Printer isn't 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)//Set to print center Esc.addselectprintmodes ( EscCommand.FONT.FONTA, ESCCOMMAND.ENable. Off, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);/set to Double power Esc.addtext ("asdfkldsjgfsdl\n")
;//Print text esc.addprintandlinefeed (); * * Print text/esc.addselectprintmodes (EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF)//Cancel times High power width esc.addselectjustification (EscCommand.JUSTIFICATION.LEFT) //Set to print left-aligned esc.addtext ("dfkdsgklfds\n");//Print text//Esc.addtext ("Welcome to use smarnet printer!\n");
Print text/////////////////////////////////////////* Print Traditional Chinese
Esc.addtext (Message, "BIG5");
Esc.addtext (Message, "GB2312");
Esc.addprintandlinefeed ();
/* Absolute location details please check the GP58 Programming Manual/Esc.addtext ("Commodity name");
Esc.addsethorandvermotionunits ((Byte) 7, (byte) 0);
Esc.addsetabsoluteprintposition ((short) 6);
Esc.addtext ("Order number");
Esc.addsetabsoluteprintposition ((short) 10);
Esc.addtext ("state");
Esc.addprintandlinefeed ();
Esc.addtext ("Apple");
Esc.addsethorandvermotionunits ((Byte) 7, (byte) 0);
Esc.addsetabsoluteprintposition ((short) 6); Esc. addtext ("12345");
Esc.addsetabsoluteprintposition ((short) 10);
Esc.addtext ("normal");
Esc.addprintandlinefeed ();
Esc.addtext ("Fruit grain orange 300ml");
Esc.addsethorandvermotionunits ((Byte) 7, (byte) 0);
Esc.addsetabsoluteprintposition ((short) 6);
Esc.addtext ("3545456");
Esc.addsetabsoluteprintposition ((short) 10);
Esc.addtext ("normal");
Esc.addprintandlinefeed (); /* Print picture//Esc.addtext ("Print bitmap!\n");
Print text//Bitmap B = Bitmapfactory.decoderesource (Getresources (), r.drawable.gprinter); Esc.addrastbitimage (b, 384, 0); Print picture/////* Print one-dimensional Barcode//Esc.addtext ("Print code128\n"); Print text//Esc.addselectprintingpositionforhricharacters (esccommand.hri_position. Set bar code height to 60 dots//Esc.addsetbarcodewidth ((byte) 1); Set the barcode unit width to 1//esc.addcode128 (Esc.gencodeb ("smarnet"));
Print Code128 code//Esc.addprintandlinefeed (); /* QRCode command to print this command only on models that support QRCode command printing. On models that do not support two-dimensional code instructions, you need to send two-dimensional barcode Pictures/Esc.addtext ("Merchant two-dimensional code \ n");//Print Text esc.addselecterrorcorrectionlEvelforqrcode ((byte) 0x31),//Set error correction level Esc.addselectsizeofmoduleforqrcode ((byte) 6);//Set QRCode module size
Esc.addstoreqrcodedata ("Dfgdgs");/set QRCode content Esc.addprintqrcode ();//print QRCode esc.addprintandlinefeed (); /* Print text */esc.addselectjustification (EscCommand.JUSTIFICATION.CENTER);//set to print left-aligned esc.addtext ("completed!\r\n");
Print end//Open Cash Box Esc.addgenerateplus (LabelCommand.FOOT.F5, (byte) 255, (byte) 255);
Esc.addprintandfeedlines ((byte) 8);
vector<byte> datas = Esc.getcommand ()//Send data 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 ();}} }

It's a good thing to print something out.

The above is a small set to introduce the Android mobile phone through Bluetooth to connect the example of a good Bo printer code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.