Search code examples
androidservicelocationlistener

Is it a good thing to starting service in new thread from activity


new Thread(new Runnable(){
            @Override
            public void run () {
                Intent firstServiceIntent=new Intent(getApplicationContext(),MyService.class);
            }
        }).start();

I have to perform background location updates in the service. I've used LocationListner in the service and it calls onLocationChanged() frequently, which can block my UI thread. If I use create thread in onLocationChanged(), every-time this method is called a new thread would be spawned. So, I'm thinking of creating the entire service in new thread instead of creating thread in onLocationChanged() . Is this a good solution or what should be the best way? Any help is appreciated.


Solution

  • If you want your service to run on a background thread, then you have two options:

    1. Use an IntentService which automatically is run on a background thread by the Android OS. Everything you do inside the IntentService will be run on the background thread. You don't need to do any threading.

    2. Use a standard Android Service and instantiate a new Thread() inside the service where you want to perform the work. The standard Android Service is run by default on the main thread so it will block your UI. That's why you have to handle the threading yourself.

    More information here: Android Services