According to the documentation:
Attention: A service runs on the main chain in your
hosting process - the service does not create its own chaining and
is not executed in a separate process (unless specified). This
means that if the service is to perform any intensive work
CPU or blocking operations (such as MP3 playback or network), you
should create a new chain within the service. Using a
separate chaining, you will reduce the risk of occurrence of errors from
Application not responding (ANR) and the main thread of
app may remain dedicated to user interaction with the
activities.
In English:
Caution: A 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). This Means that, if your
service is going to do any CPU Intensive work or blocking Operations
(such as MP3 playback or networking) , you should create a new thread
Within the service to do that work. By using a Separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application’s main thread can remain dedicated to user Interaction
with your activities.
That is, you are trying to request the main thread, so the exception occurs.
Requesting a separate thread should solve your problem.
To request a separate thread there are several forms.
The simplest is:
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
List<User> users = getUsersFromWebservice();
}
});
thread.start();
There’s Asynctask, my favorite when I’m not using Retrofit.
class UserAsync extends AsyncTask<Void, Void, List<User>>{
protected void onPreExecute (){
super.onPreExecute();
/*
Aqui é a hora pra você fazer tudo antes da requisição começar
Ex: Alterar visibilidade de algumas view, avisar usuário e etc.
*/
}
protected String doInBackground(Void...arg0) {
//Aqui você faz a requisição.
return getUsersFromWebservice();
}
protected void onPostExecute(List<User> users) {
super.onPostExecute(users);
//Aqui você tem acesso ao retorno da doInBackground(Void...arg0)
}
}
However, there is a lib called Retrofit. She, in addition to making the requisition, manages this whole threading process for you.
Also has the lib Volley, but it does not do all the request management with threads like Retrofit does, you will have to do using either of the above two examples.
This error occurs when you try to request the main thread. Most likely, when the Broadcast receiver receives an event, you’re running your function (what’s inside the service?) in the main thread. Try to place your request, wherever it is, in a separate thread.
– Max Fratane
I am running a Service within a Broadcastreceiver. Still it would be the Main ?
– rbz