java - How to prevent Bluetooth Disconnected when moving Fragment -
i make pos in android. want make printing in apps. printing i'm using bluetooth printer. then, had success make bluetooth connection , make in 1 fragment. every time move fragment bluethoot connction disconnect. please tell me how prevent bluetooth disconnect when moving fragment. in advanced
settingfragment.java
/** * simple {@link fragment} subclass. */ public class settingfragment extends fragment { public static final int message_state_change = 1; public static final int message_read = 2; public static final int message_write = 3; public static final int message_device_name = 4; public static final int message_toast = 5; public static final int message_connection_lost = 6; public static final int message_unable_connect = 7; private string mconnecteddevicename = null; // key names received bluetoothservice handler public static final string device_name = "device_name"; public static final string toast = "toast"; // intent request codes private static final int request_connect_device = 1; private static final int request_enable_bt = 2; private bluetoothadapter mbluetoothadapter = null; private bluetoothservice mservice = null; private static final string chinese = "gbk"; sessionmanagement sessionmanagement; databasehandler db; textview tvconnected; button btnscan; button btntest; public settingfragment() { // required empty public constructor } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { // inflate layout fragment view rootview = inflater.inflate(r.layout.fragment_setting, container, false); getactivity().settitle("setting"); mbluetoothadapter = bluetoothadapter.getdefaultadapter(); btnscan = (button)rootview.findviewbyid(r.id.btnscan); btntest = (button) rootview.findviewbyid(r.id.btntest); tvconnected = (textview) rootview.findviewbyid(r.id.tvprinterconnect); if (!mbluetoothadapter.isenabled()) { intent enableintent = new intent( bluetoothadapter.action_request_enable); startactivityforresult(enableintent, request_enable_bt); // otherwise, setup session } else { if (mservice == null) keylistenerinit(); } return rootview; } @suppresslint("handlerleak") private final handler mhandler = new handler() { @override public void handlemessage(message msg) { switch (msg.what) { case message_state_change: if (debug) log.i(tag, "message_state_change: " + msg.arg1); switch (msg.arg1) { case bluetoothservice.state_connected: //btnscan.settext(gettext(r.string.connecting)); btnscan.setenabled(false); break; case bluetoothservice.state_connecting: toast.maketext((mainactivity)getcontext(),r.string.title_connecting,toast.length_short).show(); break; case bluetoothservice.state_listen: case bluetoothservice.state_none: toast.maketext((mainactivity)getcontext(),r.string.title_not_connected,toast.length_short).show(); break; } break; case message_write: break; case message_read: break; case message_device_name: // save connected device's name mconnecteddevicename = msg.getdata().getstring(device_name); toast.maketext(getactivity(), "connected " + mconnecteddevicename, toast.length_short).show(); tvconnected.settext("connected "+mconnecteddevicename ); break; case message_toast: toast.maketext(getactivity(), msg.getdata().getstring(toast), toast.length_short) .show(); break; case message_connection_lost: toast.maketext(getactivity(), "device connection lost", toast.length_short).show(); tvconnected.settext("not connect device"); // edittext.setenabled(false); // sendbutton.setenabled(false); break; case message_unable_connect: toast.maketext(getactivity(), "unable connect device", toast.length_short).show(); break; } } }; @override public void onstart() { super.onstart(); // if bluetooth not on, request enabled. // setupchat() called during onactivityresult if (!mbluetoothadapter.isenabled()) { intent enableintent = new intent( bluetoothadapter.action_request_enable); startactivityforresult(enableintent, request_enable_bt); // otherwise, setup session } else { if (mservice == null) keylistenerinit(); } } @override public synchronized void onresume() { super.onresume(); if (mservice != null) { if (mservice.getstate() == bluetoothservice.state_none) { // start bluetooth services mservice.start(); } } } @override public synchronized void onpause() { super.onpause(); if (debug) log.e(tag, "- on pause -"); } @override public void onstop() { super.onstop(); if (debug) log.e(tag, "-- on stop --"); } @override public void ondestroy() { super.ondestroy(); // stop bluetooth services if (mservice != null) mservice.stop(); if (debug) log.e(tag, "--- on destroy ---"); } @override public void onactivityresult(int requestcode, int resultcode, intent data) { if (debug) log.d(tag, "onactivityresult " + resultcode); switch (requestcode) { case request_connect_device:{ // when devicelistactivity returns device connect if (resultcode == activity.result_ok) { // device mac address string address = data.getextras().getstring( devicelistactivity.extra_device_address); // bluetoothdevice object if (bluetoothadapter.checkbluetoothaddress(address)) { bluetoothdevice device = mbluetoothadapter .getremotedevice(address); // attempt connect device mservice.connect(device); } } break; } case request_enable_bt:{ // when request enable bluetooth returns if (resultcode == activity.result_ok) { // bluetooth enabled, set session keylistenerinit(); } else { // user did not enable bluetooth or error occured log.d(tag, "bt not enabled"); toast.maketext(getactivity(), r.string.bt_not_enabled_leaving, toast.length_short).show(); getactivity().onbackpressed(); } break; } } } private void keylistenerinit() { btnscan.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { intent serverintent = new intent(getactivity(), devicelistactivity.class); startactivityforresult(serverintent, request_connect_device); } }); mservice = new bluetoothservice(getactivity(), mhandler); } }
bluetoothservice.java
public class bluetoothservice { // debugging private static final string tag = "bluetoothservice"; private static final boolean debug = true; // name sdp record when creating server socket private static final string name = "zjprinter"; //uuid must // unique uuid application private static final uuid my_uuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); // member fields private bluetoothadapter madapter; private handler mhandler; private acceptthread macceptthread; private connectthread mconnectthread; private connectedthread mconnectedthread; private int mstate; // constants indicate current connection state public static final int state_none = 0; // we're doing nothing public static final int state_listen = 1; // listening incoming connections public static final int state_connecting = 2; // initiating outgoing connection public static final int state_connected = 3; // connected remote device public static string errormessage = "no_error_message"; /** * constructor. prepares new btprinter session. * @param context ui activity context * @param handler handler send messages ui activity */ public bluetoothservice(context context, handler handler) { madapter = bluetoothadapter.getdefaultadapter(); mstate = state_none; mhandler = handler; } /** * set current state of connection * @param state integer defining current connection state */ private synchronized void setstate(int state) { if (debug) log.d(tag, "setstate() " + mstate + " -> " + state); mstate = state; // give new state handler ui activity can update mhandler.obtainmessage(settingfragment.message_state_change, state, -1).sendtotarget(); } /** * return current connection state. */ public synchronized int getstate() { return mstate; } /** * start service. start acceptthread begin * session in listening (server) mode. called activity onresume() */ public synchronized void start() { if (debug) log.d(tag, "start"); // cancel thread attempting make connection if (mconnectthread != null) {mconnectthread.cancel(); mconnectthread = null;} // cancel thread running connection if (mconnectedthread != null) {mconnectedthread.cancel(); mconnectedthread = null;} // start thread listen on bluetoothserversocket if (macceptthread == null) { macceptthread = new acceptthread(); macceptthread.start(); } setstate(state_listen); } /** * start connectthread initiate connection remote device. * @param device bluetoothdevice connect */ public synchronized void connect(bluetoothdevice device) { if (debug) log.d(tag, "connect to: " + device); // cancel thread attempting make connection if (mstate == state_connecting) { if (mconnectthread != null) {mconnectthread.cancel(); mconnectthread = null;} } // cancel thread running connection if (mconnectedthread != null) {mconnectedthread.cancel(); mconnectedthread = null;} // start thread connect given device mconnectthread = new connectthread(device); mconnectthread.start(); setstate(state_connecting); } /** * start connectedthread begin managing bluetooth connection * @param socket bluetoothsocket on connection made * @param device bluetoothdevice has been connected */ public synchronized void connected(bluetoothsocket socket, bluetoothdevice device) { if (debug) log.d(tag, "connected"); // cancel thread completed connection if (mconnectthread != null) {mconnectthread.cancel(); mconnectthread = null;} // cancel thread running connection if (mconnectedthread != null) {mconnectedthread.cancel(); mconnectedthread = null;} // cancel accept thread because want connect 1 device if (macceptthread != null) {macceptthread.cancel(); macceptthread = null;} // start thread manage connection , perform transmissions mconnectedthread = new connectedthread(socket); mconnectedthread.start(); // send name of connected device ui activity message msg = mhandler.obtainmessage(settingfragment.message_device_name); bundle bundle = new bundle(); bundle.putstring(settingfragment.device_name, device.getname()); msg.setdata(bundle); mhandler.sendmessage(msg); setstate(state_connected); } /** * stop threads */ public synchronized void stop() { if (debug) log.d(tag, "stop"); setstate(state_none); if (mconnectthread != null) {mconnectthread.cancel(); mconnectthread = null;} if (mconnectedthread != null) {mconnectedthread.cancel(); mconnectedthread = null;} if (macceptthread != null) {macceptthread.cancel(); macceptthread = null;} } /** * write connectedthread in unsynchronized manner * @param out bytes write * @see connectedthread#write(byte[]) */ public void write(byte[] out) { // create temporary object connectedthread r; // synchronize copy of connectedthread synchronized (this) { if (mstate != state_connected) return; r = mconnectedthread; } r.write(out); } /** * indicate connection attempt failed , notify ui activity. */ private void connectionfailed() { setstate(state_listen); // send failure message activity message msg = mhandler.obtainmessage(settingfragment.message_toast); bundle bundle = new bundle(); bundle.putstring(settingfragment.toast, "unable connect device"); msg.setdata(bundle); mhandler.sendmessage(msg); } /** * indicate connection lost , notify ui activity. */ private void connectionlost() { //setstate(state_listen); // send failure message activity message msg = mhandler.obtainmessage(settingfragment.message_toast); bundle bundle = new bundle(); bundle.putstring(settingfragment.toast, "device connection lost"); msg.setdata(bundle); mhandler.sendmessage(msg); } /** * thread runs while listening incoming connections. behaves * server-side client. runs until connection accepted * (or until cancelled). */ private class acceptthread extends thread { // local server socket private final bluetoothserversocket mmserversocket; public acceptthread() { bluetoothserversocket tmp = null; // create new listening server socket try { tmp = madapter.listenusingrfcommwithservicerecord(name, my_uuid); } catch (ioexception e) { log.e(tag, "listen() failed", e); } mmserversocket = tmp; } @override public void run() { if (debug) log.d(tag, "begin macceptthread" + this); setname("acceptthread"); bluetoothsocket socket = null; // listen server socket if we're not connected while (mstate != state_connected) { try { // blocking call , return on // successful connection or exception socket = mmserversocket.accept(); } catch (ioexception e) { log.e(tag, "accept() failed", e); break; } // if connection accepted if (socket != null) { synchronized (bluetoothservice.this) { switch (mstate) { case state_listen: case state_connecting: // situation normal. start connected thread. connected(socket, socket.getremotedevice()); break; case state_none: case state_connected: // either not ready or connected. terminate new socket. try { socket.close(); } catch (ioexception e) { log.e(tag, "could not close unwanted socket", e); } break; } } } } if (debug) log.i(tag, "end macceptthread"); } public void cancel() { if (debug) log.d(tag, "cancel " + this); try { mmserversocket.close(); } catch (ioexception e) { log.e(tag, "close() of server failed", e); } } } /** * thread runs while attempting make outgoing connection * device. runs straight through; connection either * succeeds or fails. */ private class connectthread extends thread { private final bluetoothsocket mmsocket; private final bluetoothdevice mmdevice; public connectthread(bluetoothdevice device) { mmdevice = device; bluetoothsocket tmp = null; // bluetoothsocket connection // given bluetoothdevice try { tmp = device.createrfcommsockettoservicerecord(my_uuid); } catch (ioexception e) { log.e(tag, "create() failed", e); } mmsocket = tmp; } @override public void run() { log.i(tag, "begin mconnectthread"); setname("connectthread"); // cancel discovery because slow down connection madapter.canceldiscovery(); // make connection bluetoothsocket try { // blocking call , return on // successful connection or exception mmsocket.connect(); } catch (ioexception e) { connectionfailed(); // close socket try { mmsocket.close(); } catch (ioexception e2) { log.e(tag, "unable close() socket during connection failure", e2); } // start service on restart listening mode bluetoothservice.this.start(); return; } // reset connectthread because we're done synchronized (bluetoothservice.this) { mconnectthread = null; } // start connected thread connected(mmsocket, mmdevice); } public void cancel() { try { mmsocket.close(); } catch (ioexception e) { log.e(tag, "close() of connect socket failed", e); } } } /** * thread runs during connection remote device. * handles incoming , outgoing transmissions. */ private class connectedthread extends thread { private final bluetoothsocket mmsocket; private final inputstream mminstream; private final outputstream mmoutstream; public connectedthread(bluetoothsocket socket) { log.d(tag, "create connectedthread"); mmsocket = socket; inputstream tmpin = null; outputstream tmpout = null; // bluetoothsocket input , output streams try { tmpin = socket.getinputstream(); tmpout = socket.getoutputstream(); } catch (ioexception e) { log.e(tag, "temp sockets not created", e); } mminstream = tmpin; mmoutstream = tmpout; } @override public void run() { log.i(tag, "begin mconnectedthread"); int bytes; // keep listening inputstream while connected while (true) { try { byte[] buffer = new byte[256]; // read inputstream bytes = mminstream.read(buffer); if(bytes>0) { // send obtained bytes ui activity mhandler.obtainmessage(settingfragment.message_read, bytes, -1, buffer) .sendtotarget(); } else { log.e(tag, "disconnected"); connectionlost(); //add chongqing jinou if(mstate != state_none) { log.e(tag, "disconnected"); // start service on restart listening mode bluetoothservice.this.start(); } break; } } catch (ioexception e) { log.e(tag, "disconnected", e); connectionlost(); //add chongqing jinou if(mstate != state_none) { // start service on restart listening mode bluetoothservice.this.start(); } break; } } } /** * write connected outstream. * @param buffer bytes write */ public void write(byte[] buffer) { try { mmoutstream.write(buffer); mmoutstream.flush();//清空缓存 /* if (buffer.length > 3000) // { byte[] readata = new byte[1]; sppreadtimeout(readata, 1, 5000); }*/ log.i("btpwrite", new string(buffer,"gbk")); // share sent message ui activity mhandler.obtainmessage(settingfragment.message_write, -1, -1, buffer) .sendtotarget(); } catch (ioexception e) { log.e(tag, "exception during write", e); } } public void cancel() { try { mmsocket.close(); } catch (ioexception e) { log.e(tag, "close() of connect socket failed", e); } } } }
Comments
Post a Comment