Run Service with a Broadcastreceiver

Asked

Viewed 88 times

0

I need to run a Service through a BroadcastReceiver, but error occurs: android.os.NetworkOnMainThreadException.

To "deviate" from the error, I’m using the code below, but I want to do it the right way.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

I need to create a IntentService for this or there are other ways ?

  • 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.

  • I am running a Service within a Broadcastreceiver. Still it would be the Main ?

2 answers

2


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.

  • Max, could you give me an example of a separate thread request ?

0

With the service running and already creating the note Thread:

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                // Aqui seu conteúdo para execução

            }
        };

        Thread t = new Thread(runnable);
        t.start();
        return Service.START_STICKY;

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.