Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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;
    }
}
like image 938
Asaf Nevo Avatar asked Feb 05 '13 08:02

Asaf Nevo


People also ask

Does service run on UI thread Android?

Service is a component that is useful for performing long (or potentially long) operations without any UI. Service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

What is difference between service and thread in Android?

Service : is a component of android which performs long running operation in background, mostly with out having UI. Thread : is a O.S level feature that allow you to do some operation in the background.

Does Android service run in background thread?

Choosing between a service and a threadA service is simply a component that can run in the background, even when the user is not interacting with your application, so you should create a service only if that is what you need.

What is UI thread in Android?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.


2 Answers

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.

like image 87
koti Avatar answered Sep 25 '22 11:09

koti


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.

like image 35
ductran Avatar answered Sep 24 '22 11:09

ductran