android - How to access 'Activity' from a Service class via Intent? -
i new android programming - not have clear understanding of 'context' , 'intent'.
want know there way access activity service class? i.e. let's have 2 classes - 1 extends "activity" , other extends "service" , have created intent in activity class initiate service.
or, how access 'service' class instance 'activity' class - because in such workflow service class not directly instantiated activity-code.
public class mainactivity extends activity { . . @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); startservice(new intent(this, communicationservice.class)); . . } public class communicationservice extends service implements ..... { . . @override public int onstartcommand(final intent intent, int flags, final int startid) { super.onstartcommand(intent, flags, startid); .... } }
you can use bindservice(intent intent, serviceconnection conn, int flags)
instead of startservice
initiate service. , conn
inner class like:
private serviceconnection conn = new serviceconnection() { @override public void onserviceconnected(componentname name, ibinder service) { mmyservice = ((communicationservice.mybinder) service).getservice(); } @override public void onservicedisconnected(componentname name) { } };
mmyservice
instance of communicationservice
.
in communicationservice
, override:
public ibinder onbind(intent intent) { return new mybinder(); }
and following class in communicationservice
:
public class mybinder extends binder { public communicationservice getservice() { return communicationservice.this; } }
so can use mmyservice
access public methods , fields in activity.
in addition, can use callback interface access activity in service.
first write interface like:
public interface onchangelistener { public void onchanged(int progress); }
and in service, please add public method:
public void setonchangelistener(onchangelistener onchangelistener) { this.monchangelistener = onchangelistener; }
you can use onchanged
in service anywhere, , implement in activity:
public void onserviceconnected(componentname name, ibinder service) { mmyservice = ((communicationservice.mybinder) service).getservice(); mmyservice.setonchangelistener(new onchangelistener() { @override public void onchanged(int progress) { // want do, example update progressbar // mprogressbar.setprogress(progress); } }); }
ps: bindservice
this:
this.bindservice(intent, conn, context.bind_auto_create);
and not forget
protected void ondestroy() { this.unbindservice(conn); super.ondestroy(); }
hope helps.
Comments
Post a Comment