0

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;      
            }
        }
    }
}
4

3 回答 3

0

在您的情况下使用广播接收器要好得多。

在活动中注册它并从你的运行目标发送广播

于 2012-10-16T12:56:46.400 回答
0

使用本地广播管理器。您的服务将创建一个本地广播,并且它将可供您的应用程序使用。您可以在应用程序中为该通知编写适当的处理程序并相应地更新用户界面。

将以下代码放入您的服务中

Intent i = new Intent("NotificationServiceUpdate");
        LocalBroadcastManager.getInstance(this).sendBroadcast(i);

在您的应用程序中,将以下内容放入您要更新的活动中

     LocalBroadcastManager.getInstance(this).registerReceiver(
                mMessageReceiver, new IntentFilter("NotificationServiceUpdate"));

现在,只要服务广播任务完成,您的活动就会收到通知。您可以进一步使此广播对您的应用程序私有。

于 2012-10-16T13:01:16.753 回答
0

在这里查看我对 ScheduledExecutor 的回答:

如何在Android的后台每秒调用一段代码

并像您目前正在做的那样使用向 UI 发送的消息。

于 2012-10-16T13:18:07.703 回答