android - OnBind() called too early -


i have problem when activity call startservice() , follow bindservice() in cause npe @ onbind() in service class because thread might not finish initialize yet. in scenario how can guarantee locationthreandmessenger ready before onbind() trigger .

xxx service class

public class xxx extends service {      private static final string tag = "xxx";     private messenger locationthreadmessenger;     private locationthread locationthread;      private void onworkprepared() {         locationthreadmessenger = new messenger(locationthread.mhandler);     }      @override     public ibinder onbind(intent intent) {         return locationthreadmessenger.getbinder();     }      @override     public int onstartcommand(intent intent, int flags, int startid) {         isnewthreadnecessary();         return start_sticky;     }      private void isnewthreadnecessary() {         if (locationthread != null) {             if (locationthread.isalive()) {                 log.i(tag, "thread alive...");             } else {                 log.i(tag, "thread reused...");                 locationthread.start();             }         } else {             log.i(tag, "initializing new thread...");             locationthread = new locationthread("thread");             locationthread.start();         }     }      private class locationthread extends handlerthread {          private static final string tag = "thread";          private handler mhandler;          public locationthread(string name) {             super(name);         }          @override         protected void onlooperprepared() {             super.onlooperprepared();             mhandler = new handler(getlooper()) {                 @override                 public void handlemessage(message msg) {                  }             };             onworkprepared();             log.i(tag, "thread started...");         }     } } 

i don't know practice or not (i'm sure in not). fix. work without freeze ui

@override public ibinder onbind(intent intent) {      while (locationthreadmessenger == null) {         try {             thread.sleep(2000);         } catch (interruptedexception e) {             e.printstacktrace();         }     }      return locationthreadmessenger.getbinder(); } 

Comments