Android Connect Bluetooth printer Bluetoothadapter
Source: Https://github.com/yylxy/BluetoothText.git
public class Printactivity extends Appcompatactivity {
Device List
Private ListView ListView;
Private arraylist<printbean> Mbluetoothdevicesdatas;
Private Printadapter adapter;
Bluetooth adapter
Private Bluetoothadapter Mbluetoothadapter;
The Code of the request
public static final int request_enable_bt = 1;
Private Switch Mswitch;
Private Floatingactionbutton Mfloatingactionbutton;
Private ProgressBar Mprogressbar;
Private Toolbar Toolbar;
Private TextView Searchhint;
/**
* Start Print page
*
* @param printcontent what to print
*/
public static void Starui (context context, String printcontent) {
Intent Intent = new Intent (context, printactivity.class);
Intent.putextra ("id", id);
Intent.putextra ("Printcontent", printcontent);
Context.startactivity (Intent);
}
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Broadcast Registration
Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);
Filter.addaction (bluetoothadapter.action_discovery_finished);
Registerreceiver (mreceiver, filter); Don ' t forget to unregister during OnDestroy
Initialization
Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
Mswitch = (Switch) Findviewbyid (R.ID.SWITCH1);
Mfloatingactionbutton = (Floatingactionbutton) Findviewbyid (R.id.floatingactionbutton);
Mprogressbar = (ProgressBar) Findviewbyid (R.ID.PROGRESSBAR3);
toolbar = (toolbar) Findviewbyid (R.id.toolbar);
Searchhint = (TextView) Findviewbyid (r.id.searchhint);
Toolbar.settitle ("Select a printing Device");
ListView = (ListView) Findviewbyid (R.id.listview);
Mbluetoothdevicesdatas = new arraylist<> ();
String printcontent=getintent (). Getstringextra ("Printcontent");
adapter = new Printadapter (this, Mbluetoothdevicesdatas, Textutils.isempty (printcontent)? " 123456789 End \n\n\n ":p rintcontent);
Listview.setadapter (adapter);
Chechbluetooth ();
Addviewlistener ();
}
/**
* Determine if Bluetooth is turned on
*/
private void Chechbluetooth () {
No Bluetooth enabled
if (mbluetoothadapter! = null) {
if (!mbluetoothadapter.isenabled ()) {
Intent Intent = new Intent (bluetoothadapter.action_request_enable); Set Bluetooth visibility for up to 300 seconds
Intent.putextra (Bluetoothadapter.extra_discoverable_duration, 20);
Startactivityforresult (Intent, REQUEST_ENABLE_BT);
Setviewstatus (TRUE);
Turn on Bluetooth
} else {
Searchdevices ();
Setviewstatus (TRUE);
Mswitch.setchecked (TRUE);
}
}
}
/**
* Search Status Adjustment
*
* @param issearch whether to start search
*/
private void Setviewstatus (Boolean issearch) {
if (Issearch) {
Mfloatingactionbutton.setvisibility (View.gone);
Searchhint.setvisibility (view.visible);
Mprogressbar.setvisibility (view.visible);
} else {
Mfloatingactionbutton.setvisibility (view.visible);
Mprogressbar.setvisibility (View.gone);
Searchhint.setvisibility (View.gone);
}
}
/**
* Add view to monitor
*/
private void Addviewlistener () {
Status of Bluetooth
Mswitch.setoncheckedchangelistener (New Compoundbutton.oncheckedchangelistener () {
@Override
public void OnCheckedChanged (Compoundbutton buttonview, Boolean isChecked) {
if (isChecked) {
Openbluetooth ();
Setviewstatus (TRUE);
} else {
Closebluetooth ();
}
}
});
Re-search
Mfloatingactionbutton.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (View v) {
if (mswitch.ischecked ()) {
Searchdevices ();
Setviewstatus (TRUE);
} else {
Openbluetooth ();
Setviewstatus (TRUE);
}
}
});
Toolbar.setnavigationicon (R.DRAWABLE.IC_ARROW_BACK_BLACK_24DP);
Toolbar.setnavigationonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (view view) {
Toast.maketext (Printactivity.this, "n", Toast.length_short). Show ();
}
});
}
@Override
protected void Onactivityresult (int requestcode, int resultcode, Intent data) {
Super.onactivityresult (Requestcode, ResultCode, data);
if (ResultCode = = Result_ok && Requestcode = = REQUEST_ENABLE_BT) {
LOG.E ("text", "Turn on Bluetooth");
Searchdevices ();
Mswitch.setchecked (TRUE);
Mbluetoothdevicesdatas.clear ();
Adapter.notifydatasetchanged ();
} else if (ResultCode = = result_canceled && Requestcode = = REQUEST_ENABLE_BT) {
LOG.E ("text", "No Bluetooth turned on");
Mswitch.setchecked (FALSE);
Setviewstatus (FALSE);
}
}
/**
* Turn on Bluetooth
*/
public void Openbluetooth () {
Intent Intent = new Intent (bluetoothadapter.action_request_enable); Set Bluetooth visibility for up to 300 seconds
Intent.putextra (Bluetoothadapter.extra_discoverable_duration, 20);
Startactivityforresult (Intent, REQUEST_ENABLE_BT);
}
/**
* Turn off Bluetooth
*/
public void Closebluetooth () {
Mbluetoothadapter.disable ();
}
/**
* Search for Bluetooth devices
*/
public void Searchdevices () {
Mbluetoothdevicesdatas.clear ();
Adapter.notifydatasetchanged ();
Start searching for Bluetooth devices
Mbluetoothadapter.startdiscovery ();
}
/**
* Search for Bluetooth devices by radio
*/
Private final Broadcastreceiver mreceiver = new Broadcastreceiver () {
public void OnReceive (context context, Intent Intent) {
String action = Intent.getaction ();
Add the search settings to the collection
if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
Bluetoothdevice device = Intent.getparcelableextra (Bluetoothdevice.extra_device);
Devices that have been matched
if (device.getbondstate () = = bluetoothdevice.bond_bonded) {
Addbluetoothdevice (device);
No matching devices
} else {
Addbluetoothdevice (device);
}
Adapter.notifydatasetchanged ();
Search Complete
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (ACTION)) {
Setviewstatus (FALSE);
}
}
/**
* Add data
* @param device Bluetooth Settings object
*/
private void Addbluetoothdevice (Bluetoothdevice device) {
for (int i = 0; i < mbluetoothdevicesdatas.size (); i++) {
if (Device.getaddress (). Equals (Mbluetoothdevicesdatas.get (i). GetAddress ())) {
Mbluetoothdevicesdatas.remove (i);
}
}
if (device.getbondstate () = = bluetoothdevice.bond_bonded && device.getbluetoothclass (). Getdeviceclass () = = Print_type) {
Mbluetoothdevicesdatas.add (0, new Printbean (device));
} else {
Mbluetoothdevicesdatas.add (new Printbean (device));
}
}
};
}
Class Printadapter extends Baseadapter {
Private arraylist<printbean> Mbluetoothdevicesdatas;
Private Context Mcontext;
Bluetooth adapter
Private Bluetoothadapter Mbluetoothadapter;
Bluetooth Socket Object
Private Bluetoothsocket Mmsocket;
Private UUID uuid;
The printed output stream
private static OutputStream outputstream = null;
Search for pop-up window tips
ProgressDialog progressdialog = null;
Private final int exceptioncod = 100;
What to print
Private String mprintcontent;
Updating the UI when printing exceptions
Handler Handler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
if (msg.what = = exceptioncod) {
Toast.maketext (Mcontext, "Print send failed, please try again later", Toast.length_short). Show ();
if (progressdialog! = null) {
Progressdialog.dismiss ();
}
}
}
};
/**
* @param context Contexts
* @param mbluetoothdevicesdatas Device List
* @param printcontent Printed content
*/
Public Printadapter (context context, arraylist<printbean> Mbluetoothdevicesdatas, String printcontent) {
This.mbluetoothdevicesdatas = Mbluetoothdevicesdatas;
Mcontext = context;
Mbluetoothadapter = Bluetoothadapter.getdefaultadapter ();
Mprintcontent = printcontent;
UUID = uuid.fromstring ("00001101-0000-1000-8000-00805F9B34FB");
}
public int GetCount () {
return Mbluetoothdevicesdatas.size ();
}
@Override
Public Object getItem (int position) {
return position;
}
@Override
public long getitemid (int position) {
return position;
}
@Override
Public View GetView (final int position, View Convertview, ViewGroup parent) {
Convertview = Layoutinflater.from (Mcontext). Inflate (r.layout.itme, NULL);
View icon = Convertview.findviewbyid (R.id.icon);
TextView name = (TextView) Convertview.findviewbyid (r.id.name);
TextView address = (TextView) Convertview.findviewbyid (r.id.address);
TextView start = (TextView) Convertview.findviewbyid (R.id.start);
Final Printbean Databean = mbluetoothdevicesdatas.get (position);
Icon.setbackgroundresource (Databean.gettypeicon ());
Name.settext (Databean.name);
Address.settext (Databean.isconnect? "Connected": "Not Connected");
Start.settext (Databean.getdevicetype (start));
Click Connect and Print
Convertview.setonclicklistener (New View.onclicklistener () {
@Override
public void OnClick (View v) {
try {
If it is already connected and is a printer
if (Databean.isconnect && databean.gettype () = = Print_type) {
if (mbluetoothadapter.isenabled ()) {
New Connectthread (Mbluetoothadapter.getremotedevice (databean.address)). Start ();
ProgressDialog = Progressdialog.show (Mcontext, "Prompt", "Printing ...", true);
} else {
Toast.maketext (Mcontext, "Bluetooth is not turned on", Toast.length_short). Show ();
}
No connection
} else {
is the printer
if (databean.gettype () = = Print_type) {
SetConnect (Mbluetoothadapter.getremotedevice (databean.address), position);
Not a printer
} else {
Toast.maketext (Mcontext, "The device is not a printer", Toast.length_short). Show ();
}
}
} catch (Exception e) {
E.printstacktrace ();
}
}
});
return convertview;
}
/**
* Matching Device
*
* @param device devices
*/
private void SetConnect (Bluetoothdevice device, int position) {
try {
Method Createbondmethod = BluetoothDevice.class.getMethod ("Createbond");
Createbondmethod.invoke (device);
Mbluetoothdevicesdatas.get (position). SetConnect (True);
Notifydatasetchanged ();
} catch (Exception e) {
E.printstacktrace ();
}
}
/**
* Send data
*/
public void Send (String senddata) {
try {
byte[] data = senddata.getbytes ("GBK");
Outputstream.write (data, 0, data.length);
Outputstream.flush ();
Outputstream.close ();
Progressdialog.dismiss ();
} catch (IOException e) {
E.printstacktrace ();
Handler.sendemptymessage (EXCEPTIONCOD); Send a message to handler to update the UI
}
}
/**
* Connect as Client
*/
Private class Connectthread extends Thread {
Public Connectthread (Bluetoothdevice device) {
try {
Mmsocket = Device.createrfcommsockettoservicerecord (UUID);
} catch (IOException e) {
E.printstacktrace ();
}
}
public void Run () {
Cancel the discovery because it will slow down the connection
Mbluetoothadapter.canceldiscovery ();
try {
Connecting sockets
Mmsocket.connect ();
The connection succeeded in getting the output stream
OutputStream = Mmsocket.getoutputstream ();
Send (Mprintcontent);
} catch (Exception connectexception) {
LOG.E ("Test", "Connection Failed");
Connectexception.printstacktrace ();
Update UI when sending messages on exception
Message msg = new Message ();
Msg.what = Exceptioncod;
Send a message to handler to update the UI
Handler.sendmessage (msg);
try {
Mmsocket.close ();
} catch (Exception closeexception) {
Closeexception.printstacktrace ();
}
Return
}
}
}
}
Android connects to a Bluetooth printer Bluetoothadapter