Search code examples
androidandroid-serviceandroid-2.3-gingerbread

GUI freezes on periodically returning data from service to activity


I have created a Service in android which can send data to the activity on a regular interval.

so far i have create an activity which binds with the service which i have created. but the problem my activity gets freez when i am sending message back to the activity which is previously bind. i have create this example based on MessengerService example from API Demo samples.

following is a code written in a service class and inside that i have create a IncomingHandler

case MSG_SET_VALUE:

mValue = msg.arg1;

for (int i=mClients.size()-1; i>=0; i--) {

    final Messenger local = mClients.get(i);
    final int index = i;
    counterThread = new Thread(new Runnable(){
    @Override
    public void run() {
        // TODO Auto-generated method stub
        int j=0;                

        while(true){

            try {
                Thread.sleep(6000);
                local.send(Message.obtain(null,
                    MSG_SET_VALUE, j++, 0));
                Log.d("Thread " , j + "");
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                 mClients.remove(index);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }           

        }

    }




    });
counterThread.run();



}
break;

so when i send a message from activity using following code , above case will get triggered.

         msg = Message.obtain(null,
                 MyService.MSG_SET_VALUE, this.hashCode(), 0);
         mService.send(msg);

and i am handling the incoming message in a activity

 class IncomingHandler extends Handler {
         @Override
         public void handleMessage(Message msg) {
             switch (msg.what) {
                 case MyService.MSG_SET_VALUE:

                     System.out.println("DATA" + msg.arg1);
                    //   mCallbackText.setText("Received from service: " + msg.arg1);

                     break;
           }
       }
    }

so i want to know tht is this the right way to get data periodically from Service or am i missing something here


Solution

  • counterThread.run();
    

    This is a bad method. You will call start() to run thread properly :

    counterThread.start();