I want to create a service similar to this one, (reference from Here), to download multiple files asynchronously in Android.
public static class DownloadingService extends IntentService {
public static String PROGRESS_UPDATE_ACTION = DownloadingService.class
.getName() + ".newDownloadTask";
private ExecutorService mExec;
private CompletionService<NoResultType> mEcs;
private LocalBroadcastManager mBroadcastManager;
private List<DownloadTask> mTasks;
public DownloadingService() {
super("DownloadingService");
mExec = Executors.newFixedThreadPool( 3 ); // The reason to use multiple thread is to download files asynchronously.
mEcs = new ExecutorCompletionService<NoResultType>(mExec);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
while(true)
{
if( cursor <= totalDownloadQueue.size() -1) { //totalDownloadQueue is a static ArrayList which contains numerous DownloadTask
mEcs.submit(totalDownloadQueue.get(cursor));
cursor++; // The variable cursor is also a static int variable.
}
}// continuously observing the totalDownloadQueue. If any download item is added. Then the thread are dispatched to handle that.
mExec.shutdown();
}
The user can select download items among listview
in different fragments. My strategy is that as the user select the items and press download button, these items are passed into DownloadTask
which is responsible for downloading a file. Then the download tasks are added into the totalDownloadQueue
.
Here are some questions:
I know the
intentservice
is triggered by some defined action. But what I want to is to create a background service watching thetotalDownloadQueue
, if any newdownloadtask
is availabe, then some thread are called to operate the tasks.What's the side effect if I did so for this customized
intentservice
?What alternative class should I use? Please provide
sample code
along with the explanation, thanks.As I know, the initialization of the threads is only called by once. If I start the service at the beginning of the application and the threads should be killed as the user terminate the app.(I mean when he
swipe out
the window.) Do the threads exist after the user exit the application?If this approach still can't resolve the issue about downloading files asynchronously? What other strategy should I adopt? Please provide some example code or reference so that I can modify on it.
I have spent 7 days dealing with the complex requirement, any help please!