Search code examples
javaandroidmultithreadingserviceandroid-asynctask

AsyncTask or service or thread for storing into data base


Say, I got 10k data that needs storing in the database ( I'm estimating this will take bout a minute at most ) but this data is not needed for the UI.

What's the best way to store this? Using asyncTask? Service? Or threads?

And if I were to use asyncTask / threads will they still stay "active" for a minute even if the activity is closed?


Solution

  • The JobIntentService might be the choice. It's not activity-related, will not be destroyed with an activity.

    How to use:

    1. Manifest,
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
    <service android:name=".YourService" android:permission="android.permission.BIND_JOB_SERVICE" />
    
    1. Create the service:
    public class YourService extends JobIntentService {
    
        public static final int JOB_ID = 1;
    
        public static void enqueueWork(Context context, Intent work) {
            enqueueWork(context, YourService.class, JOB_ID, work);
        }
    
        @Override
        protected void onHandleWork(@NonNull Intent intent) {
            // Your jobs are here
        }
    
    }
    
    1. Start the job somewhere: YourService.enqueueWork(context, new Intent());