如何从服务中更新UI?

问题描述

With regard to this post,基本上,我将$listMeasure = $list | Measure-Object $listCount = $listMeasure.Count 注册到了我的服务(我只是将正在运行的活动的引用传递给了该服务)并从那里更新了我的UI。但是我的困惑是,如果MainActivity是一个单独的线程(不是UI线程),而我正在从Service线程调用UI更新,为什么它起作用? AFAIK,应该只有UI线程才能调用UI更新,对吧?

作为参考,我只是从相关文章中重新发布有关如何从Service更新UI的代码:

service

解决方法

默认情况下,服务在主线程上运行,这根本不是问题。而且,您认为仅通过参考的方式不是一个好习惯。您可以做的是绑定到服务并在通过活动实例之前获取服务实例。

内部服务onBind使用LocalBinder返回服务,而在活动中使用ServiceConnection连接到服务

protected ServiceConnection mServerConn = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name,IBinder binder) {
        Log.d(LOG_TAG,"onServiceConnected");
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(LOG_TAG,"onServiceDisconnected");
    }
}

public void start() {
    // mContext is defined upper in code,I think it is not necessary to explain what is it 
    mContext.bindService(intent,mServerConn,Context.BIND_AUTO_CREATE);
    mContext.startService(intent);
}

public void stop() {
    mContext.stopService(new Intent(mContext,ServiceRemote.class));
    mContext.unbindService(mServerConn);
}

在您的服务中这样的事情

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

onServiceConnected将返回活页夹实例。使用binder.getService()并将您的工作代码放在此处。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...