androidandroid-studioandroid-asynctaskandroid-servicethread-priority

Android: AsyncTask more priority than Service


I have a Service and AsyncTask running at the same time, Inside the service, storing the data in the server takes place, In AsyncTask, getting data from a different source and updating UI takes place.

UI doesn't get updated until the the task inside the Service gets completed, after that UI gets displayed

protected List<AppItem> doInBackground(MyTaskParams... integers) {
            android.os.Process.setThreadPriority(THREAD_PRIORITY_BACKGROUND + THREAD_PRIORITY_MORE_FAVORABLE);

I used the above code for asynctask , but its not working, how can I give more preference to AsyncTask than Service


Solution

  • By default, Service runs on the Main thread.

    Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.

    https://developer.android.com/guide/components/services?hl=en#should-you-use-a-service-or-a-thread

    It looks like you start your Service first, then you run your AsyncTask. Because the service runs in the Main thread, your AsyncTask is not started until it finishes.

    Update

    There are many solutions and the choice depends on requirements. It looks like in your case the simplest way to achieve concurrency is to use the IntentService. So, you can start both the IntentService and AsyncTask from your Activity.

    public class MyIntentService extends IntentService 
    {  
    
        private static final String TAG = this.getClass().getSimpleName();
    
        public MyIntentService() {
            super("MyIntentService");
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) 
        {
            super.onStartCommand(intent, flags, startId);
            Log.d(TAG, "MyIntentService Started");
            // This thing still happens on ui thread
    
            return START_NOT_STICKY;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) 
        {
            Log.d(TAG, "MyIntentService Handling Intent");
            // Your work should be here, it happens on non-ui thread
        }
    }
    

    https://developer.android.com/reference/android/app/IntentService