Skip to content

Instantly share code, notes, and snippets.

@vuhung3990
Created February 13, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vuhung3990/b1d30fc86c8b55a38d8d871b990c6d29 to your computer and use it in GitHub Desktop.
Save vuhung3990/b1d30fc86c8b55a38d8d871b990c6d29 to your computer and use it in GitHub Desktop.
simple IntentService task queue - limit: can't update queue when running
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");
}
}
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment