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;
}
}
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.
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.
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.
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.
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 BroadcastReceiver
s to fire an Intent
whenever a server responds.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With