Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/65856375/asynctask-or-service-or-thread-for-storing-into-data-base

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...