android - Call service method from activity -
i need call function service when item options menu pressed:
if (id == r.id.action_connect) { if (misbound) { localservice.connect(); // cannot referenced static context } }
i'm using these docs. read few answers i'm not sure one.
you can call startservice(someintent);
for example activity can this
intent serviceintent = new intent(this, theservice.class); serviceintent.addcategory("some_unique_string"); startservice(serviceintent);
then in service
public int onstartcommand(intent intent, int flags, int startid) { if (intent != null) { if (intent.hascategory("some_unique_string")) { themethodyouwanttocall(); } else if (intent.hascategory("some_other_string")) { someothermethod(); } } return start_sticky; }
you can call startservice like.
the basic idea create intent represents "intended" method want call , in service onstartcommand method, figure out method should call based on information pass in via intent , call method.
note: must check intent not null. if system ever kills , restarts service, calling startservice null intent, if leave part out will @ point npe crash.
Comments
Post a Comment