您的位置:首页 > 其它

Service学习——第五篇 使用IntentService在单独线程上执行异步任务

2014-09-21 14:57 507 查看
Service学习——使用IntentService在单独的线程上执行异步任务

特点:它可以在任务执行完成后自动结束服务。

Service类需要我们手动去终止,但是有很多时候我们忘记了终止它,或者不知道什么时候去终止,这时IntentService我感觉就会很好用。

使用方法:

首先,定义一个MyIntentService类来继承IntentService

接着,实现onHandleIntent()方法

代码如下:

package com.example.myservice;

import java.net.URL;

import android.app.IntentService;

import android.content.Intent;

import android.util.Log;

public class MyIntentService extendsIntentService {

publicMyIntentService(String name) {

super(name);

//TODO Auto-generated constructor stub

}

publicMyIntentService(){

super("MyIntentService");

}

@Override

protectedvoid onHandleIntent(Intent intent) {

//TODO Auto-generated method stub

try{

intresult = DownloadFile(new URL("http://www.baidu.com"));

Log.d("IntentService","Download" + result + "bytes");

}catch (Exception e) {

//TODO: handle exception

e.printStackTrace();

}

}

privateint DownloadFile(URL url){

try{

Thread.sleep(5000);

}catch (InterruptedException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

return100;

}

}

别忘记在Manifest中声明这个服务:

<serviceandroid:name="com.example.myservice.MyIntentService"></service>

改动MainActivity:

Intent intent = new Intent(MainActivity.this,MyIntentService.class);

startService(intent);

运行这个程序,大概5秒钟,你会在LogCat中看到运行结果:Download 100bytes
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: