android - How to implement Bluetooth Connectivity Actively into multiple Activities using Application Class or Service Class -
i new bluetooth connection process flow. working mini thermal printer device android application. device has own sdk.
when activity finishes or gets destroyed connection device being lost. how modify following code prevent happening.
printdemo activity package com.zj.printdemo; import com.zj.printdemo.r; import android.content.intent; import com.zj.btsdk.bluetoothservice; import com.zj.btsdk.printpic; import android.annotation.suppresslint; import android.app.activity; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.os.bundle; import android.os.handler; import android.os.message; import android.view.view; import android.widget.button; import android.widget.edittext; import android.widget.toast; import android.util.log; public class printdemo extends activity { button btnsearch; button btnsenddraw; button btnsend; button btnclose; edittext edtcontext; edittext edtprint; private static final int request_enable_bt = 2; bluetoothservice mservice = null; bluetoothdevice con_dev = null; private static final int request_connect_device = 1; //��ȡ�豸��Ϣ /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); mservice = new bluetoothservice(this, mhandler); //�����������˳����� if( mservice.isavailable() == false ){ toast.maketext(this, "bluetooth not available", toast.length_long).show(); finish(); } } @override public void onstart() { super.onstart(); //����δ�������� if( mservice.isbtopen() == false) { intent enableintent = new intent(bluetoothadapter.action_request_enable); startactivityforresult(enableintent, request_enable_bt); } try { btnsenddraw = (button) this.findviewbyid(r.id.btn_test); btnsenddraw.setonclicklistener(new clickevent()); btnsearch = (button) this.findviewbyid(r.id.btnsearch); btnsearch.setonclicklistener(new clickevent()); btnsend = (button) this.findviewbyid(r.id.btnsend); btnsend.setonclicklistener(new clickevent()); btnclose = (button) this.findviewbyid(r.id.btnclose); btnclose.setonclicklistener(new clickevent()); edtcontext = (edittext) findviewbyid(r.id.txt_content); btnclose.setenabled(false); btnsend.setenabled(false); btnsenddraw.setenabled(false); } catch (exception ex) { log.e("������Ϣ",ex.getmessage()); } } @override protected void ondestroy() { super.ondestroy(); if (mservice != null) mservice.stop(); mservice = null; } class clickevent implements view.onclicklistener { public void onclick(view v) { if (v == btnsearch) { intent serverintent = new intent(printdemo.this,devicelistactivity.class); //��������һ����Ļ startactivityforresult(serverintent,request_connect_device); } else if (v == btnsend) { string msg = edtcontext.gettext().tostring(); if( msg.length() > 0 ){ mservice.sendmessage(msg+"\n", "gbk"); } } else if (v == btnclose) { mservice.stop(); } else if (v == btnsenddraw) { string msg = ""; string lang = getstring(r.string.strlang); //printimage(); byte[] cmd = new byte[3]; cmd[0] = 0x1b; cmd[1] = 0x21; if((lang.compareto("en")) == 0){ cmd[2] |= 0x10; mservice.write(cmd); //��������ģʽ mservice.sendmessage("congratulations!\n", "gbk"); cmd[2] &= 0xef; mservice.write(cmd); //ȡ�����ߡ�����ģʽ msg = " have sucessfully created communications between device , our bluetooth printer.\n\n" +" company high-tech enterprise specializes" + " in r&d,manufacturing,marketing of thermal printers , barcode scanners.\n\n"; mservice.sendmessage(msg,"gbk"); }else if((lang.compareto("ch")) == 0){ cmd[2] |= 0x10; mservice.write(cmd); //��������ģʽ mservice.sendmessage("��ϲ����\n", "gbk"); cmd[2] &= 0xef; mservice.write(cmd); //ȡ�����ߡ�����ģʽ msg = " ���Ѿ��ɹ��������������ǵ�������ӡ����\n\n" + " ����˾��һ��רҵ�����з�����������������Ʊ�ݴ�ӡ��������ɨ���豸��һ��ĸ߿Ƽ���ҵ.\n\n"; mservice.sendmessage(msg,"gbk"); } } } } /** * ����һ��handlerʵ�������ڽ���bluetoothservice��ػ�������Ϣ */ private final handler mhandler = new handler() { @override public void handlemessage(message msg) { switch (msg.what) { case bluetoothservice.message_state_change: switch (msg.arg1) { case bluetoothservice.state_connected: //������ toast.maketext(getapplicationcontext(), "connect successful", toast.length_short).show(); btnclose.setenabled(true); btnsend.setenabled(true); btnsenddraw.setenabled(true); break; case bluetoothservice.state_connecting: //�������� log.d("��������","��������....."); break; case bluetoothservice.state_listen: //�������ӵĵ��� case bluetoothservice.state_none: log.d("��������","�ȴ�����....."); break; } break; case bluetoothservice.message_connection_lost: //�����ѶϿ����� toast.maketext(getapplicationcontext(), "device connection lost", toast.length_short).show(); btnclose.setenabled(false); btnsend.setenabled(false); btnsenddraw.setenabled(false); break; case bluetoothservice.message_unable_connect: //�������豸 toast.maketext(getapplicationcontext(), "unable connect device", toast.length_short).show(); break; } } }; @override public void onactivityresult(int requestcode, int resultcode, intent data) { switch (requestcode) { case request_enable_bt: //��������� if (resultcode == activity.result_ok) { //�����Ѿ��� toast.maketext(this, "bluetooth open successful", toast.length_long).show(); } else { //�û������������ finish(); } break; case request_connect_device: //��������ijһ�����豸 if (resultcode == activity.result_ok) { //�ѵ�������б��е�ij���豸�� string address = data.getextras() .getstring(devicelistactivity.extra_device_address); //��ȡ�б������豸��mac��ַ con_dev = mservice.getdevbymac(address); mservice.connect(con_dev); } break; } } //��ӡͼ�� @suppresslint("sdcardpath") private void printimage() { byte[] senddata = null; printpic pg = new printpic(); pg.initcanvas(384); pg.initpaint(); pg.drawimage(0, 0, "/mnt/sdcard/icon.jpg"); senddata = pg.printdraw(); mservice.write(senddata); //��ӡbyte������ } }
devicelistactivity
public class devicelistactivity extends activity { // return intent public static string extra_device_address = "device_address"; // member fields bluetoothservice mservice = null; private arrayadapter<string> mpaireddevicesarrayadapter; private arrayadapter<string> mnewdevicesarrayadapter; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // setup window requestwindowfeature(window.feature_indeterminate_progress); setcontentview(r.layout.device_list); //��ʾ�б���� // set result canceled incase user backs out setresult(activity.result_canceled); // initialize button perform device discovery button scanbutton = (button) findviewbyid(r.id.button_scan); scanbutton.setonclicklistener(new onclicklistener() { public void onclick(view v) { dodiscovery(); v.setvisibility(view.gone); } }); // initialize array adapters. 1 paired devices , // 1 newly discovered devices mpaireddevicesarrayadapter = new arrayadapter<string>(this, r.layout.device_name); mnewdevicesarrayadapter = new arrayadapter<string>(this, r.layout.device_name); // find , set listview paired devices listview pairedlistview = (listview) findviewbyid(r.id.paired_devices); pairedlistview.setadapter(mpaireddevicesarrayadapter); pairedlistview.setonitemclicklistener(mdeviceclicklistener); // find , set listview newly discovered devices listview newdeviceslistview = (listview) findviewbyid(r.id.new_devices); newdeviceslistview.setadapter(mnewdevicesarrayadapter); newdeviceslistview.setonitemclicklistener(mdeviceclicklistener); // register broadcasts when device discovered intentfilter filter = new intentfilter(bluetoothdevice.action_found); this.registerreceiver(mreceiver, filter); // register broadcasts when discovery has finished filter = new intentfilter(bluetoothadapter.action_discovery_finished); this.registerreceiver(mreceiver, filter); mservice = new bluetoothservice(this, null); // set of paired devices set<bluetoothdevice> paireddevices = mservice.getpaireddev(); // if there paired devices, add each 1 arrayadapter if (paireddevices.size() > 0) { findviewbyid(r.id.title_paired_devices).setvisibility(view.visible); (bluetoothdevice device : paireddevices) { mpaireddevicesarrayadapter.add(device.getname() + "\n" + device.getaddress()); } } else { string nodevices = getresources().gettext(r.string.none_paired).tostring(); mpaireddevicesarrayadapter.add(nodevices); } } @override protected void ondestroy() { super.ondestroy(); if (mservice != null) { mservice.canceldiscovery(); } mservice = null; this.unregisterreceiver(mreceiver); } /** * start device discover bluetoothadapter */ private void dodiscovery() { // indicate scanning in title setprogressbarindeterminatevisibility(true); settitle(r.string.scanning); // turn on sub-title new devices findviewbyid(r.id.title_new_devices).setvisibility(view.visible); // if we're discovering, stop if (mservice.isdiscovering()) { mservice.canceldiscovery(); } // request discover bluetoothadapter mservice.startdiscovery(); } // on-click listener devices in listviews private onitemclicklistener mdeviceclicklistener = new onitemclicklistener() { //����б�������豸 public void onitemclick(adapterview<?> av, view v, int arg2, long arg3) { // cancel discovery because it's costly , we're connect mservice.canceldiscovery(); // device mac address, last 17 chars in view string info = ((textview) v).gettext().tostring(); string address = info.substring(info.length() - 17); // create result intent , include mac address intent intent = new intent(); intent.putextra(extra_device_address, address); log.d("���ӵ�ַ", address); // set result , finish activity setresult(activity.result_ok, intent); finish(); } }; // broadcastreceiver listens discovered devices , // changes title when discovery finished private final broadcastreceiver mreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { string action = intent.getaction(); // when discovery finds device if (bluetoothdevice.action_found.equals(action)) { // bluetoothdevice object intent bluetoothdevice device = intent.getparcelableextra(bluetoothdevice.extra_device); // if it's paired, skip it, because it's been listed if (device.getbondstate() != bluetoothdevice.bond_bonded) { mnewdevicesarrayadapter.add(device.getname() + "\n" + device.getaddress()); } // when discovery finished, change activity title } else if (bluetoothadapter.action_discovery_finished.equals(action)) { setprogressbarindeterminatevisibility(false); settitle(r.string.select_device); if (mnewdevicesarrayadapter.getcount() == 0) { string nodevices = getresources().gettext(r.string.none_found).tostring(); mnewdevicesarrayadapter.add(nodevices); } } } }; }
i tried remove ondestroy
, seems not work.
activities in android designed provide user interface. therefore, once activity goes in background, system may stop anytime. when activity stops, doing stopped too.
if don't need user interaction , need maintain bluetooth connection in background, should use service. activity needs launch service , let run. if activity stops after this, service keep running.
there 2 things keep running service indefinitely; create service using startservice() , return start_sticky onstartcommand(). these 2 steps, service may shut down system should restart immediately.
google doc has example of implementing this:
http://developer.android.com/guide/components/services.html#extendingservice
Comments
Post a Comment