如何在android服务中使用线程/计时器并更新UI?

时间:2012-10-16 12:49:04

标签: android multithreading service timer

我正在开发一个启动服务的Android应用程序。服务将在每个固定的时间间隔后执行一些代码并将结果结束到活动。活动应该将结果显示给用户。

首先我用线程试了一下。 为了在固定间隔之后执行服务,我创建一个线程 - 执行代码,获得结果 - 将此结果发送到活动以供显示 - 让线程在一段固定的时间间隔内休眠。 但它没有按预期工作。代码由线程执行。线程进入休眠状态,然后在休眠时间间隔结束后将结果发送到活动结束。要求是在线程代码执行获得结果后必须立即更新UI。

我也尝试过使用Timer和TimerTask。但它给出了与上面相同的结果。 请帮帮我。

服务类

@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);
}

活动类

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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

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

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

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

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

答案 2 :(得分:0)

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

how to call a section of code every second in background in Android

并将消息用于UI,就像您当前正在做的那样。