他们使用的是多线程套筒轮。
意味着,有一个 ForegroundService 处理服务中的不同线程。
ForegroundService 确保它保持活动状态。线程本身是在后台线程中运行的单个进程。
有几个可用的 ThreadExecutor 可确保您只有几个线程并行运行或逐个线程处理它们。
这是一个制作 SocketWheel 的好教程http://www.javaspecialists.eu/archive/Issue023.html
来源:
线程执行器http://developer.android.com/reference/java/util/concurrent/ThreadPoolExecutor.html
ThreadPoolExecutorExectuorService vs ThreadPoolExecutor (which is using LinkedBlockingQueue)
前台服务Android - implementing startForeground for a service?
已编辑:一些代码
public class DLService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification note=new Notification(R.drawable.somegraphics, "some title", randomnr);
Intent i=new Intent(this, ActivityClassToOpenWhenClicked.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi=PendingIntent.getActivity(this, 0, i, 0);
note.setLatestEventInfo(this, "downloadmanager","downloading.. nothing", pi);
note.flags|=Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
// if (intent.hasExtra("dlurl")) {
new Thread(new Runnable() {
public void run() {
new Client("http://yourfile.com/file.jpg");
}
}).start();
return START_NOT_STICKY;
}
class Client {
public Client(String filetodownload) throws Exception {
//do your http connection. for example one download #
// HttpUrlConnection httpConnection = new .....
}
}
}
这只是一个快速编码示例,未经测试。但它显示了这个概念。
服务本身接受一个 Intent,它可以是文件所在的 url。然后它创建一个新的线程来完成这项工作。只要下载文件,线程就会运行。 foregroundService 确保服务将保持活动状态。您还可以创建一个 ThreadPoolExecutor,它在 onec 上处理多个线程。阅读http://developer.android.com/training/multiple-threads/create-threadpool.html 获取说明。