ITeye博客

【Android】IntentService多线程

dyingbleed · 2011-10-25 19:56 · Android多线程 · 移动开发 · Markdown

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 此處省略具體實現
		}
		
	}

}

评论(2)

  1. #2 楼 · dyingbleed · 2013-06-06 17:19

    kangsoft writes:

    IntentService 里貌似不用再创建线程啊。。

    Service在单独的一个进程里,这里是展示在Service进程中使用多线程

  2. #1 楼 · kangsoft · 2013-05-03 16:45

    IntentService 里貌似不用再创建线程啊。。

评论功能维护中,当前仅展示历史评论。