问题描述
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()
并将您的工作代码放在此处。