使用IntentService在Service中创建耗时任务

IntentService是Service的子类,比普通的Service增加了额外的功能。

Service存在两个问题:

1,Service不会专门启动一条单独的线程,Service与它所在应用访问者位于同一条线程

2,Service也不是专门一条新线程,因此不应该在Service中直接处理耗时任务

IntentService的特点:

1,IntentService将会使用队列来管理请求Intent,每当客户端代码通过In疼痛与请求启动IntentService时,IntentService会将Intent加入队列,然后启动一条新的worker线程来处理该Intent。

2,IntentService使用新的worker线程处理intent请求,因此不会阻塞主线程。

3,IntentService会创建单独的worker线程来处理onHandleIntent()方法实现的代码

4,所有请求处理完成后,IntentService会自动停止,不用调用stopSelf方法来停止Service

5,为Service的onBind()方法提供了默认实现,默认实现的onBind()方法返回null

6,为Service的onStarCommand()方法提供的默认实现,会把请求Intent添加到队列中

在Service中执行耗时任务的方法:

A,使用普通Service,在OnCreate中创建线程

B,使用IntentService,重写onHandleIntent()方法创建耗时任务


使用IntentService时,只需要继承IntentService,重写onHandleIntent()就行了


IntentServiceTest.java

public class IntentServiceTest extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	public void startIntentService(View source)
	{
		// 创建需要启动的IntentService的Intent
		Intent intent = new Intent(this, MyIntentService.class);
		// 启动IntentService
		startService(intent);
	}
}
MyIntentService.java

public class MyIntentService extends IntentService//继承IntentService
{
	public MyIntentService()
	{
		super("MyIntentService");
	}

	// IntentService会使用单独的线程来执行该方法的代码
	@Override
	protected void onHandleIntent(Intent intent)
	{
		// 该方法内可以执行任何耗时任务,比如下载文件等,此处只是让线程暂停20秒
		long endTime = System.currentTimeMillis() + 20 * 1000;
		System.out.println("onStart");
		while (System.currentTimeMillis() < endTime)
		{
			synchronized (this)
			{
				try
				{
					wait(endTime - System.currentTimeMillis());
				}
				catch (Exception e)
				{
				}
			}
		}
		System.out.println("---耗时任务执行完成---");
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值