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.
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.
I have also tried using Timer and TimerTask. But it gives the same result as above. Please help me on this.
Service class
@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);
}
Activity class
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;
}
}
}
}