vuhung3990
2/13/2017 - 8:06 AM

simple IntentService task queue - limit: can't update queue when running

simple IntentService task queue

  • limit: can't update queue when running
Intent intent = new Intent(new Intent(getApplicationContext(), SyncService.class));
                intent.putExtra(SyncService.TASK_KEY, new int[]{
                        SyncService.SYNC_CONTACT,
                        SyncService.SYNC_GROUP,
                        SyncService.SYNC_HISTORY
                });
                startService(intent);
                
                
                
// logcat

// task sync contact
02-13 14:48:58.891 31917-32026/com.example.tux.mylab D/service: service contact is started
02-13 14:49:00.891 31917-32026/com.example.tux.mylab D/service: job contact done!

// task sync group
02-13 14:49:01.938 31917-32026/com.example.tux.mylab D/service: service group is started
02-13 14:49:03.939 31917-32026/com.example.tux.mylab D/service: job group done!

02-13 14:49:04.547 31917-32026/com.example.tux.mylab D/service: service contact is started
02-13 14:49:06.547 31917-32026/com.example.tux.mylab D/service: job contact done!

02-13 14:49:07.018 31917-32026/com.example.tux.mylab D/service: service history is started
02-13 14:49:09.019 31917-32026/com.example.tux.mylab D/service: job history done!

// when everything done -> close service
02-13 14:49:09.019 31917-31917/com.example.tux.mylab D/service: service is destroyed
public class SyncService extends IntentService {
    public static final String TASK_KEY = "";
    public static final int SYNC_CONTACT = 2;
    public static final int SYNC_HISTORY = 1;
    public static final int SYNC_GROUP = 0;

    public SyncService() {
        super(null);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        int[] tasks = intent.getIntArrayExtra(TASK_KEY);
        for (int task : tasks) {
            switch (task) {
                case SYNC_HISTORY:
                    runTask("history");
                    break;
                case SYNC_CONTACT:
                    runTask("contact");
                    break;
                case SYNC_GROUP:
                    runTask("group");
                    break;
                default:
                    break;
            }
        }
    }

    private void runTask(String uniqueTaskName) {
        Log.d("service", "service " + uniqueTaskName + " is started");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            Log.d("service", "job " + uniqueTaskName + " done!");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("service", "service is destroyed");
    }
}