Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use thread / timer in android service and update UI?
    primarykey
    data
    text
    <p>I am developing an android application which will start a service.The service will execute some code after every fixed interval of time and end the result to the activity.The activity should display the result to the user.</p> <p>First I tried it with a thread. For the service to execute after a fixed interval I create a thread - execute the code, get the result - send this result to activity for display - put the thread to sleep for a some fixed time interval. But it is not working as expected.The code is executed by the thread. The thread goes to sleep and then the result is sent to the activity at the end after the sleep time interval. The requirement is the UI must be immediately updated after the result is obtained by the thread code execution. </p> <p>I have also tried using Timer and TimerTask. But it gives the same result as above. Please help me on this.</p> <p><strong>Service class</strong> </p> <pre><code>@Override public int onStartCommand(Intent intent, int flags, int startId) { td = new ThreadDemo(); td.start(); } private class ThreadDemo extends Thread { @Override public void run() { super.run(); String result = //code executes here and returns a result sendMessageToUI(result); //method that will send result to Activity ThreadDemo.sleep(5000); } } private void sendMessageToUI(String strMessage) { Bundle b = new Bundle(); b.putString(“msg”, strMessage); Message msg = Message.obtain(null, 13); msg.setData(b); } </code></pre> <p><strong>Activity class</strong></p> <pre><code>public class MyActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } class IncomingHandler extends Handler { @Override public void handleMessage(Message msg) { System.out.println("in ui got a msg................"); switch (msg.what) { case 13: System.out.println("setting status msg.............."); String str1 = msg.getData().getString("msg"); textview.setText(str1); break; } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload