Android Service and UI Thread
Asked Answered
L

2

11

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.

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;
    }
}
Lowrey answered 5/2, 2013 at 8:19 Comment(1)
a service runs on the ui thread. take a look at intentservice for services that run a part of the process on a separated threadTremendous
B
27

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.

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 BroadcastReceivers to fire an Intent whenever a server responds.

Bagasse answered 5/2, 2013 at 8:38 Comment(0)
Y
5

As far I know, Android service run on UI thread. If you want to make an asynchronous job, you should use Intent Service
See: What is the difference between an IntentService and a Service?
Here is an Intent service example you can try.

Yeta answered 5/2, 2013 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.