---
title: "【Android】IntentService多线程"
author: "dyingbleed"
date: "2011-10-25T19:56:47Z"
tags: []
categories: ["移动开发"]
slug: "android-intentservice"
draft: false
lastmod: "2011-10-25T19:57:13Z"
id: 1214088
url: "https://dyingbleed.iteye.com/blog/1214088"
---

IntentService继承自Service，用于异步处理通过startService(Intent intent)方法传递的Intent对象。

该Service根据需要启动

，通过实现onHandleIntent(Intent intent)方法，IntentService会在一个工作线程中，

按顺序处理每个Intent对象，直到当工作执行完毕自动销毁。

 

 

 

实例代码

 

1、启动服务

 

 

```
Intent intent = new Intent("iteye.dyingbleed.DownloadService");
intent.putExtra("url", url); //添加下载地址
startService(intent);
```

 

2、配置AndroidManifest

 

3、新建DownloadService类，继承IntentService

 

 

```
package lizhen.apk;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.IntentService;
import android.content.Intent;

public class DownloadService extends IntentService {
	
	private ExecutorService pool;

	public DownloadService() {
		super("DownloadService");
	}

	@Override
	public void onCreate() {
		super.onCreate();
		pool = Executors.newCachedThreadPool();
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String url = intent.getStringExtra("url");
		pool.execute(new DownloadTask(url));
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		pool.shutdown();
	}
	
	private class DownloadTask implements Runnable {
		
		private final String url;
		
		public DownloadTask(String url) {
			this.url = url;
		}

		@Override
		public void run() {
			// TODO 此處省略具體實現
		}
		
	}

}
```