android - How to bind an Activity to a Service and control and manage the Service from the Activity -



android - How to bind an Activity to a Service and control and manage the Service from the Activity -

i'm trying bind activity localservice interact it. in activity able create calls methods defined in localbinder , not in localservice. doing wrong?

not starting scratch read question , have read little how code sample code , code resembles sample code. have been reading of service documentation convenience here little quote section of documentation:

"a service "bound" when application component binds calling bindservice(). a bound service offers client-server interface allows components interact service, send requests, results, , across processes interprocess communication (ipc). bound service runs long application component bound it. multiple components can bind service @ once, when of them unbind, service destroyed."

but can't that. mentioned above best can have activity phone call methods defined in localbinder. have achieved nil part highlighted in black above.

if helps here relevant portions of code.

localservice bound to:

/************************************************************************************************** * filename: localservice.java * project name: local service sample * application name: local service * description: file contains localservice (extends service) our local service app **************************************************************************************************/ bundle com.marie.localservicesample; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.uuid; import android.app.notification; import android.app.notificationmanager; import android.app.pendingintent; import android.app.service; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.intent; import android.os.bundle; import android.os.ibinder; import android.os.looper; import android.os.message; import android.os.messenger; import android.os.remoteexception; import android.util.log; import android.widget.toast; public class localservice extends service { private notificationmanager mnm; // unique identification number notification. // utilize on notification start, , cancel it. private int notification = r.string.local_service_started; // arbitrary numbers test purposes public static int statuscode = 99; public static int emptymsg = 549; // extras onstartcommand , utilize in serviceworker() thread public static final string extra_mac = "com.marie.localservicesample.extra_mac"; private string macstring; public static final string extra_messenger = "com.marie.localservicesample.extra_messenger"; private messenger messenger; private static final uuid my_uuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); //private static final string macstring = "00:06:66:02:d0:ec"; boolean stop_receive_data = false; // object receives interactions clients. see // remoteservice more finish illustration - or not because // local service private final ibinder mbinder = new localbinder(); @override public ibinder onbind(intent intent) { log.i("onbind", "called in localservice" ); log.i("onbind", "intent: " + intent.tostring()); log.i("onbind", "mbinder: " + mbinder); homecoming mbinder; } @override public void oncreate() { mnm = (notificationmanager)getsystemservice(notification_service); // display notification starting. set icon in status bar. shownotification(); } // phone call @ end of onstartcommand() after got extras public void afterstartcommand() { thread thr = new thread(null, new serviceworker(), "localservice"); thr.start(); } /* * serviceworker thread passes messages handler defined in * controller activity. */ class serviceworker implements runnable { public void run() { // background processing here... simple looper.prepare(); bluetoothadapter btadapter = bluetoothadapter.getdefaultadapter(); bluetoothdevice btdevice = btadapter.getremotedevice(macstring); bluetoothsocket btsocket = null; inputstream btistream = null; outputstream btostream = null; seek { btsocket = btdevice.createrfcommsockettoservicerecord(my_uuid); } grab (ioexception e1) { e1.printstacktrace(); } seek { btsocket.connect(); } grab (ioexception e1) { e1.printstacktrace(); } seek { btistream = btsocket.getinputstream(); btostream = btsocket.getoutputstream(); } grab (ioexception e1) { e1.printstacktrace(); } seek { int info = btistream.read(); // reset bluetooth device while (data != 63) { log.d("localservice", "resetting bluetooth device"); btostream.write('r'); info = btistream.read(); } stringbuffer strbuffer = new stringbuffer(""); boolean databegin = false; int ndxplus = 0; while (data != -1) { char printableb = (char) data; if (data < 32 || info > 126) { //printableb = ' '; } //log.d("localservice", character.tostring(printableb) + "(" + info + ")"); if (data == 63) { btostream.write('$'); btostream.write(','); } if (data == 45) { btostream.write('1'); btostream.write(','); databegin = true; } if (databegin == true) { strbuffer = strbuffer.append(character.tostring(printableb)); } if (data == 13) { databegin = false; //log.d("localservicedatastring", strbuffer.tostring()); // send info handler plot info message msg = message.obtain(); msg.what = controller.message_mac; msg.obj = strbuffer; seek { messenger.send(msg); } grab (remoteexception e) { e.printstacktrace(); } strbuffer = new stringbuffer(""); if (ndxplus < 0) { btostream.write('+'); ndxplus++; } } info = btistream.read(); if (stop_receive_data) info = -1; } } grab (ioexception e1) { e1.printstacktrace(); } seek { btsocket.close(); } grab (ioexception e1) { e1.printstacktrace(); } localservice.this.stopself(); looper.loop(); // stop service when done... // or utilize unbindbtn in mainactivity class? } } @override public int onstartcommand(intent intent, int flags, int startid) { log.i("localservice", "received start id " + startid + ": " + intent); bundle extras = intent.getextras(); messenger = (messenger)extras.get(extra_messenger); macstring = extras.getstring(extra_mac); afterstartcommand(); // want service go on running until explicitly // stopped, homecoming sticky. homecoming start_sticky; } @override public void ondestroy() { // cancel persistent notification. mnm.cancel(notification); stop_receive_data = true; // tell user stopped. toast.maketext(this, r.string.local_service_stopped, toast.length_short).show(); } /** * show notification while service running. */ private void shownotification() { // in sample, we'll utilize same text ticker , expanded notification charsequence text = gettext(r.string.local_service_started); // set icon, scrolling text , timestamp notification notification = new notification(r.drawable.stat_sample, text, system.currenttimemillis()); // pendingintent launch our activity if user selects notification pendingintent contentintent = pendingintent.getactivity(this, 0, new intent(this, controller.class), 0); // set info views show in notification panel. notification.setlatesteventinfo(this, gettext(r.string.local_service_label), text, contentintent); // send notification. mnm.notify(notification, notification); } }

activity binds localservice:

/************************************************************************************************** * filename: binding.java * project name: local service sample * application name: local service * description: file contains binding class our local service application **************************************************************************************************/ bundle com.marie.localservicesample; import android.app.activity; import android.content.componentname; import android.content.context; import android.content.intent; import android.content.serviceconnection; import android.os.bundle; import android.os.ibinder; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.toast; /* * illustration of binding , unbinding local service. * demonstrates implementation of service client * bind to, receiving object through can communicate service. */ public class binding extends activity { private ilocalbinder mboundservice; private boolean misbound; private serviceconnection mconnection = new serviceconnection() { public void onserviceconnected(componentname classname, ibinder service) { // called when connection service has been // established, giving service object can utilize // interact service. because have bound explicit // service know running in our own process, can // cast ibinder concrete class , straight access it. mboundservice = (ilocalbinder)service; int statuscode = mboundservice.getstatuscode(); log.d("binding.java","called onserviceconnected. statuscode: " + statuscode); toast.maketext(binding.this, r.string.local_service_connected, toast.length_short).show(); } public void onservicedisconnected(componentname classname) { // called when connection service has been // unexpectedly disconnected -- is, process crashed. // because running in our same process, should never // see happen. mboundservice = null; log.d("binding", "called onservicedisconnected"); toast.maketext(binding.this, r.string.local_service_disconnected, toast.length_short).show(); } }; void dobindservice() { // found connection service. utilize explicit // class name because want specific service implementation // know running in our own process (and won't // supporting component replacement other applications). bindservice(new intent(binding.this, localservice.class), mconnection, context.bind_auto_create); misbound = true; } void dounbindservice() { if (misbound) { int statuscode = mboundservice.getstatuscode(); if (statuscode != 0) log.d("dounbindservice", "binding.java statuscode: " + statuscode); // tell user did unbind toast.maketext(this, r.string.local_service_unbound, toast.length_short).show(); // detach our existing connection. unbindservice(mconnection); misbound = false; } } @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.local_service_binding); // watch button clicks. button button = (button)findviewbyid(r.id.bind); button.setonclicklistener(mbindlistener); button = (button)findviewbyid(r.id.unbind); button.setonclicklistener(munbindlistener); } private onclicklistener mbindlistener = new onclicklistener() { public void onclick(view v) { dobindservice(); } }; private onclicklistener munbindlistener = new onclicklistener() { public void onclick(view v) { dounbindservice(); } }; @override protected void ondestroy() { super.ondestroy(); dounbindservice(); } }

my ilocalbinder , localbinder:

/************************************************************************************************** * filename: ilocalbinder.java * project name: local service sample * application name: local service * description: file contains illustration interface localbinder **************************************************************************************************/ bundle com.marie.localservicesample; public interface ilocalbinder { public int getstatuscode(); } /************************************************************************************************** * filename: localbinder.java * project name: local service sample * application name: local service * description: file contains localbinder class our local service application **************************************************************************************************/ bundle com.marie.localservicesample; import android.os.binder; import com.marie.localservicesample.localservice; /** * class clients access. because know service * runs in same process clients, don't need deal * ipc. */ public class localbinder extends binder implements ilocalbinder { @override public int getstatuscode() { homecoming localservice.statuscode; } }

thanks!

see local service example.

just re-create binder class code have service instead of making separate file it: (inside localservice class declaration)

public class localservice { // object receives interactions clients. see // remoteservice more finish example. private final ibinder mbinder = new localbinder(); /** * class clients access. because know service * runs in same process clients, don't need deal * ipc. */ public class localbinder extends binder { localservice getservice() { homecoming localservice.this; } } ... }

and then:

public void onserviceconnected(componentname classname, ibinder service) { // called when connection service has been // established, giving service object can utilize // interact service. because have bound explicit // service know running in our own process, can // cast ibinder concrete class , straight access it. mboundservice = ((localservice.localbinder)service).getservice();

now can access service straight using mboundservice.

android multithreading service interface local

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

intellij idea - Update external libraries with intelij and java -

javascript - send data from a new window to previous window in php -