我的情况是,我需要每3 MB下载30个zip文件,并在用户首次登录时解压缩所有下载的文件。根据OREO背景限制,现在我正在安排一个工作来执行此任务。但是这里的问题是,如果我依次下载所有zip,则需要花费时间。我需要在使用线程池执行程序运行线程的后台并行运行此任务。但是,一旦我使用线程池执行器,就无法弄清楚如何停止我的工作。我如何获得一个回调,说所有的zip文件都已下载。安排工作是正确的后台工作方式,还是应该使用工作管理器?我需要确保此任务一直执行到结束?
下面是线程池执行程序类:
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class MyThreadPoolExecutor {
private static MyThreadPoolExecutor MyThreadPoolExecutor;
private static int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
private static final TimeUnit KEEP_ALIVE_TIME_UNIT;
private final BlockingQueue<Runnable> mDownloadWorkQueue;
private final ThreadPoolExecutor mDownloadThreadPool;
private static final int CORE_POOL_SIZE = 8;
private static final int MAXIMUM_POOL_SIZE = 8;
private static final int KEEP_ALIVE_TIME = 1;
private Handler mHandler;
// A static block that sets class fields
static {
// The time unit for "keep alive" is in seconds
KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
// Creates a single static instance of PhotoManager
MyThreadPoolExecutor = new MyThreadPoolExecutor();
}
private MyThreadPoolExecutor() {
mDownloadWorkQueue = new LinkedBlockingQueue<Runnable>();
mDownloadThreadPool = new ThreadPoolExecutor(NUMBER_OF_CORES * 2, NUMBER_OF_CORES * 2,
KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, mDownloadWorkQueue);
mHandler = new Handler(Looper.getMainLooper()) {
/*
* handleMessage() defines the operations to perform when the
* Handler receives a new Message to process.
*/
@Override
public void handleMessage(Message inputMessage) {
}
};
}
public static MyThreadPoolExecutor getInstance() {
return MyThreadPoolExecutor;
}
public void addThread(Runnable runnable){
mDownloadWorkQueue.add(runnable);
}
public void execute(Runnable runnable){
MyThreadPoolExecutor.mDownloadThreadPool.execute(runnable);
}
}
下面是我的可运行代码:
public class SimpleThread implements Runnable {
private String file_url;
public SimpleThread( String url) {
this.file_url = url;
}
@Override
public void run() {
try{
URL url = new URL(file_url.replaceAll(" ", "%20"));
InputStream fileInputStream = url.openStream();
if(fileInputStream != null) {
lessonmediaSaver.save(fileInputStream);
String source = "path";
String destination = "destinationpath";
new UnzipUtility().unzip(source,destination);
System.out.println("Saving Zip --> ");
}else{
System.out.println("Zip not saved --> ");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
这是我执行工作服务代码的方式:
for(MyObject myObject:myObjectArray){
SimpleThread simpleThread = new SimpleThread(myObject.getFileUrl());
IstarThreadPoolExecutor.getInstance().execute(simpleThread);
}