Android pad connect Bluetooth printer gprinter---realize bluetooth printing function

Source: Internet
Author: User
Tags connect socket getcolor

I. Overview

A recent project has a need to go through the pad Bluetooth to connect the L Bluetooth printer to print documents, is to click a button to trigger the generation of documents >> save to the database

>> bluetooth printing. First want to implement Bluetooth connection, then go to call Gprinter SDK, here I use Gprinter SDK2.1 version, and SDK2.2 and SDK2.1

of the API has a different place, here is the example of SDK2.1.

Second, use

1, first to import the jar package, add dependencies, if there is no SDK2.1 version can go to http://download.csdn.net/download/zabio/9382570 download,

I'm using eclipse here.

2. Add Permissions

<!--manage permissions for Bluetooth devices --
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>
<!--permission to use a Bluetooth device--
<uses-permission android:name= "Android.permission.BLUETOOTH"/>

<uses-permission android:name= "Android.permission.WAKE_LOCK"/>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

3. Register the Print service in the Androidmanifest.xml file

        <service            android:name= "Com.gprinter.service.GpPrintService"            android:label= "Gpprintservice            " android:process= ": Remote"            android:enabled= "true"            android:exported= "true" >            <intent-filter>                <action android:name= "Com.gprinter.aidl.GpPrintService"/>            </intent-filter>        

4 ,   with the new package named Com.gprinter.aidl, add the Gpservice.aidl file to the package with the following code:

Package com.gprinter.aidl;interface gpservice{      int openport (int printerid,int porttype,string Devicename,int PortNumber);   void Closeport (int printerid);    int getprinterconnectstatus (int printerid);    int printetestpage (int printerid);       int queryprinterstatus (int printerid,int timesout);   int getprintercommandtype (int printerid);    int Sendesccommand (int printerid, String b64);    int Sendtsccommand (int printerid, String  b64);}


5, in the OnCreate initialization method inside start and bind service, I here is fragment, so use the context.

Variable I put here, if there is an error, modify it yourself

Private intconnectstate;private String deviceaddress;//bluetooth MAC address private Bluetoothsocket socket;//bluetooth socketprivate connectthread mthread;//connected bluetooth thread private mybroadcastrece Iver receiver;//Bluetooth Search broadcast private gpservicemgpservice= null;private printerserviceconnectionmconn= null;p Rivate bluetoothadapteradapter;//Bluetooth Adapter private bluetoothdevice Mbluetoothdevice; Bluetooth device private void StartService () {Intent i = new Intent (Mcontext, Gpprintservice.class); Mcontext.startservice (i); tr Y {thread.sleep (+);} catch (Interruptedexception e) {e.printstacktrace ()}} public void Connection () {mconn = new printerserviceconnection (); Intent Intent = new Intent (" Com.gprinter.aidl.GpPrintService "); Intent.setpackage (Mcontext.getpackagename ()); Mcontext.bindservice (Intent, Mconn, context.bind_auto_create); Bindservice}class Printerserviceconnection implements Serviceconnection {@Overridepublic voID onservicedisconnected (componentname name) {LOGGER.E ("serviceconnection", "onservicedisconnected () called"); Mgpservice = null;} @Overridepublic void onserviceconnected (componentname name, IBinder service) {LOGGER.E ("serviceconnection", " Onserviceconnected () called "); Mgpservice = GpService.Stub.asInterface (service);}};

Connect Bluetooth, because it is the first time to use Bluetooth to call the printing, here is only my own method, cancel the Pairing dialog box does not necessarily succeed.
public void Searchbluetoothdevice () {//check whether the device supports Bluetooth adapter = Bluetoothadapter.getdefaultadapter (); if (adapter = = null) {/ /device does not support Bluetooth toast.maketext (mcontext, "Your device doesn ' t supports Bluetooth", 0). Show (); return;} If Bluetooth is turned off, turn on Bluetooth if (!adapter.isenabled ()) {LOGGER.E (TAG, "Device Close"), Intent Intent = new Intent ( bluetoothadapter.action_request_enable); Intent.putextra (bluetoothadapter.extra_discoverable_duration, 300); return;} Gets the paired Bluetooth device set<bluetoothdevice> devices = Adapter.getbondeddevices ();//traverse int count = 0;for (bluetoothdevice Paireddevice:devices) {if (paireddevice.getname () = = null) {return;} else if (Paireddevice.getname (). StartsWith (" Gprinter ")) {count++;d eviceaddress = paireddevice.getaddress ();//assignment is global variable mbluetoothdevice = Adapter.getremotedevice ( deviceaddress);//Connect Bluetooth connect (deviceaddress, mbluetoothdevice); break;}} Count=0, description No pairing, search device if (adapter.isenabled () && count = = 0) {adapter.startdiscovery (), if (receiver! = null) {MCo Ntext.unregisterreceiver (receiver); rEceiver = null;} Set broadcast information filtering 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); Intentfilter.addaction (bluetoothdevice.action_bond_state_changed); if (receiver = = NULL) {receiver = new Mybroadcastreceiver ();//Register a broadcast receiver, receive and process search results mcontext.registerreceiver (receiver, intentfilter);}} public class Mybroadcastreceiver extends Broadcastreceiver {@Overridepublic 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 = = null) {return;} if (device.getname () = = null) {return;} if (Device.getname (). StartsWith ("Gprinter")) {deviceaddress = Device.getaddress (); LOGGER.E (TAG, Device.getname () + "---ACTion_found "); Adapter.canceldiscovery (); mbluetoothdevice = Adapter.getremotedevice (deviceaddress); connectState = Device.getbondstate (); switch (connectstate) {//Not paired case bluetoothdevice.bond_none://pairing try {setpin ( Mbluetoothdevice.getclass (), Mbluetoothdevice, "0000"); Method Createbondmethod = Mbluetoothdevice.getclass (). GetMethod ("Createbond"); Createbondmethod.invoke ( Mbluetoothdevice); Cancelpairinguserinput (Mbluetoothdevice.getclass (), mbluetoothdevice);} catch (Exception e) {e.printstacktrace ();} break;//is paired with Case BluetoothDevice.BOND_BONDED:if (Device.getname (). StartsWith ("Gprinter")) {Connect (deviceaddress, Mbluetoothdevice);} Break;}}} else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals (ACTION)) {//Status change broadcast bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device); if (device.getname () = = null) {return;} if (Device.getname (). StartsWith ("Gprinter")) {deviceaddress = Device.getaddress (); LOGGER.E (TAG, Device.getname () + "---action_bond_state_changed"); MBLUETOOTHDEvice = Adapter.getremotedevice (deviceaddress); connectstate = Device.getbondstate (); switch (connectstate) {case Bluetoothdevice.bond_none:break;case Bluetoothdevice.bond_bonding:break;case BluetoothDevice.BOND_BONDED:if ( Device.getname (). StartsWith ("Gprinter")) {Connect (deviceaddress, mbluetoothdevice);} Break;}}}} @SuppressWarnings ({"Rawtypes", "Unchecked"}) public boolean setpin (Class btclass, Bluetoothdevice btdevice, String str) Throws Exception {try {Method Removebondmethod = Btclass.getdeclaredmethod ("Setpin", new class[] {byte[].class}); Boolean returnvalue = (Boolean) Removebondmethod.invoke (Btdevice, new object[] {str.getbytes ()}); LOG.E ("ReturnValue", "" "+ ReturnValue);} catch (SecurityException e) {e.printstacktrace ();} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( Exception e) {e.printstacktrace ();} return true;} Cancels user input @suppresswarnings ({"Unchecked", "rawtypes"}) public boolean cancelpairinguserinput (Class Btclass, Bluetoothdevice device) throws Exception {Method Createbondmethod = Btclass.getmethod ("Cancelpairinguserinput");//cancelbondprocess () Boolean returnvalue = (Boolean) createbondmethod.invoke (device); return Returnvalue.booleanvalue ();} /** * Start the thread method connecting Bluetooth * * @param macAddress * @param device */public synchronized void Connect (String macAddress, Bluetoothde Vice device) {if (mthread! = null) {mthread.interrupt (); mthread = null;} if (socket! = NULL) {try {mgpservice.closeport (0);} catch (Exception e) {e.printstacktrace ();} socket = NULL;} Mthread = new Connectthread (macAddress, device); Mthread.start ();} Private class Connectthread extends Thread {private Bluetoothdevicemmdevice;private Outputstreammmoutstream;public Connectthread (String mac, bluetoothdevice device) {mmdevice = device; String spp_uuid = "00001101-0000-1000-8000-00805F9B34FB"; try {if (socket = = NULL) {socket = Device.createrfcommsockettoservicerecord (uuid.fromstring (Spp_uuid));}} catch (Exception e) {e.printstacktrace ();}} public void Run () {//Cancel discovery BecausE It'll slow down the connectionadapter.canceldiscovery (); try {//Connect the device through the socket. This would block//until it succeeds or throws an EXCEPTIONLOGGER.E (TAG, "connect socket"), if (socket.isconnected ()) {LOGGER.E (TA G, "already Connected");} else {//Socket.connect (); if (socket! = NULL) {try {logger.e (TAG, Mgpservice + "--1--" + mbluetoothdevice); if (Mgpservice ! = null) {int state = Mgpservice.getprinterconnectstatus (0); switch (state) {case Gpdevice.state_connected:break;case GPDEVICE.STATE_LISTEN:LOGGER.E (Tag, "State:state_listen"); break;case GPDEVICE.STATE_CONNECTING:LOGGER.E (Tag, " State:state_connecting "); break;case gpdevice.state_none:logger.e (TAG," State:state_none "); RegisterBroadcast (); Mgpservice.openport (0, 4, mbluetoothdevice.getaddress (), 0); BREAK;DEFAULT:LOGGER.E (TAG, "State:default"); break;}} else {LOGGER.E (TAG, "Mgpservice is NULL");} } catch (Exception e) {e.printstacktrace ();} Connecttoprinter ();}}} catch (Exception connectexception) {//Unable to connect; close theSocket and get OUTLOGGER.E (TAG, "Unable to connect"), try {if (socket! = NULL) {mgpservice.closeport (0); socket = null;//Co Mmonutils.showtoast (Mcontext, "failed to connect");}} catch (Exception closeexception) {//failed to close Socket}return;}}} public static final stringaction_connect_status= "Action.connect.status";p rivate void Registerbroadcast () { Intentfilter filter = new Intentfilter (); filter.addaction (action_connect_status); Mcontext.registerreceiver ( Printerstatusbroadcastreceiver, filter);} Private broadcastreceiverprinterstatusbroadcastreceiver= New Broadcastreceiver () {@Overridepublic void OnReceive ( Context context, Intent Intent) {if (Action_connect_status.equals (Intent.getaction ())) {int type = Intent.getintextra ( Gpprintservice.connect_status, 0); int id = Intent.getintextra (gpprintservice.printer_id, 0); if (type = = Gpdevice.state _connecting) {LOGGER.E (tag, "state_connecting"),} else if (type = = Gpdevice.state_none) {LOGGER.E (tag, "State_none");} else if (type = = Gpdevice.state_valid_printer) {LOGGER.E (tag, "State_valid_printer"),} else if (type = = Gpdevice.state_invalid_printer) {LOGGER.E (tag , "State_invalid_printer");} else if (type = = gpdevice.state_connected) {LOGGER.E (TAG, "state_connected"); Mcontext.unregisterreceiver ( Printerstatusbroadcastreceiver); getprinterstatusclicked (ID);} else if (type = = Gpdevice.state_listen) {LOGGER.E (TAG, "State_listen");}} public void getprinterstatusclicked (int id) {try {int status = Mgpservice.queryprinterstatus (0, 500); String str = new String (), if (status = = Gpcom.state_no_err) {str = "printer normal"; int state = Mgpservice.getprintercommandtype (0)  if (state = = Gpcom.esc_command) {printdata ();} else {}} else if ((byte) (Status & Gpcom.state_offline) > 0) {str = "The printer is out of service,please try again!";} else if ((byte) (Status & Gpcom.state_paper_err) > 0) {str = "There is no Pager in the printer!";} else if ((byte) (Status & Gpcom.state_cover_open) > 0) {str = "The COVER of the printer is not closed!";} else if ((byte) (Status & Gpcom.state_err_occurs) > 0) {str = "The printer made a mistake!";} Toast.maketext (Mcontext, "printer:" + ' 0 ' + "status:" + str, toast.length_short). Show ();}  catch (RemoteException E1) {//TODO auto-generated catch Blocke1.printstacktrace ();}}


7, the contents of the Printdata () method, refer to the following:


8, the key code is the call of the Sendescconmand method, but the length of the SDK2.1 printing bar code is limited, so you can generate my own one-dimensional code picture let go to play

Printing: Com.google.zxing package of one-dimensional code printing, Import jar Package: can be downloaded online

Private Bitmap Getcodebitmap (String str) {int size = Str.length (); for (int i = 0; i < size; i++) {int c = Str.charat (i) if ((19968 <= c && C < 40623)) {//Toast.maketext (Createcodeactivity.this, "the time to generate barcodes cannot be Chinese", toast.length_s Hort). Show (); return null;}} Bitmap bmp = Null;try {if (str! = NULL &&! "). Equals (str)) {BMP = Createonedcode (str);}} catch (Writerexception e) {e.printstacktrace ();} return bmp;} /** * Used to generate a given content into a one-dimensional code note: The current generation of content in Chinese will be directly error, to modify the contents of the underlying JAR package * * @param content * will generate the contents of a one-dimensional code * * @return return the generated code bit Map * @throws writerexception * writerexception exception */public Bitmap createonedcode (String content) throws Writer Exception {//Generate a one-dimensional barcode, specify the size when encoding, do not generate the picture and then scale it, which blurs the recognition failure Bitmatrix matrix = Null;matrix = new Multiformatwriter (). Encode (content,barcodeformat.code_128, 260, n); int width = matrix.getwidth (); int height = matrix.getheight (); int[] pixels = NE W int[width * height];for (int y = 0; y < height; y++) {for (int x = 0; x < width; x+ +) {if (Matrix.get (x, y)) {pixels[y * width + x] = Mcontext.getresources (). GetColor (r.color.black);} else {pixels[y * wid th + x] = Mcontext.getresources (). GetColor (R.color.white);;}} Bitmap Bitmap = Bitmap.createbitmap (width, height,bitmap.config.argb_8888);//Generate Bitmap through the array of pixels, Specific reference apibitmap.setpixels (pixels, 0, width, 0, 0, width, height); return bitmap;}

9, printed barcode to pass in a string--I am here is a field in the entity class


Third, after the language

The first time to write a blog, there may be some problems, I hope you forgive me if you do not understand can leave a message.




Android pad connect Bluetooth printer gprinter---realize bluetooth printing function

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.