Android服务和UI线程 [英] Android Service and UI Thread
问题描述
我的应用程序中正在运行服务.
I have a Service running in my app..
此服务具有一个用于向服务器发送消息的对象,以及一个用于获取和使用该对象的功能.
This Service has an object for sending message to the server and a function to get that object and use it.
该对象是通过Service初始化的,但是当UI获取此对象并使用它时-看起来它在UI线程上使用了它..
The object is initialized from the Service and yet when the UI gets this objects and use it - it looks like it uses it on the UI Thread..
这是正确的吗?有没有一种方法可以使我的对象始终从服务线程运行?
Is this correct ? Is there a way i can make my object always run from the Service Thread ?
public class ServerMessagesManager extends Service {
private ServerMessagesReceiver serverMessageReceiver;
@Override
public void onCreate() {
super.onCreate();
this.serverMessageReceiver = new ServerMessagesReceiver(app);
}
public ServerMessagesReceiver getServerMessagesReceiver()
{
return serverMessageReceiver;
}
}
推荐答案
使用 IntentService
代替 Service
.如果您在 Service
中进行网络呼叫,则UI将会卡住.因此,请使用 IntentService
,因为它使用了单独的 Thread
.
Use IntentService
instead of Service
. If you do network calls in a Service
, the UI will stuck. Therefore, use an IntentService
since it uses a separate Thread
.
并且您不知道服务器消息何时将检索数据.如果仍在进行网络调用,则在访问对象时可能引发 NullPointerException
.每当服务器响应时,使用 BroadcastReceiver
s触发 Intent
.
And you do not know when a server message will retrieve the data. A NullPointerException
could be thrown if objects are accessed as long as network calls are still in progress. Use BroadcastReceiver
s to fire an Intent
whenever a server responds.
这篇关于Android服务和UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!