IntentService多线程

来源:互联网 发布:linux虚拟机和双系统 编辑:程序博客网 时间:2024/05/18 02:44

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

该Service根据需要启动

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

 

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

 

 

 

 

 

实例代码

 

1、启动服务

 

 

Java代码  收藏代码
  1. Intent intent = new Intent("iteye.dyingbleed.DownloadService");  
  2. intent.putExtra("url", url); //添加下载地址  
  3. startService(intent);  

 

2、配置AndroidManifest

 

3、新建DownloadService类,继承IntentService

 

 

Java代码  收藏代码
  1. package lizhen.apk;  
  2.   
  3. import java.util.concurrent.ExecutorService;  
  4. import java.util.concurrent.Executors;  
  5.   
  6. import android.app.IntentService;  
  7. import android.content.Intent;  
  8.   
  9. public class DownloadService extends IntentService {  
  10.       
  11.     private ExecutorService pool;  
  12.   
  13.     public DownloadService() {  
  14.         super("DownloadService");  
  15.     }  
  16.   
  17.     @Override  
  18.     public void onCreate() {  
  19.         super.onCreate();  
  20.         pool = Executors.newCachedThreadPool();  
  21.     }  
  22.   
  23.     @Override  
  24.     protected void onHandleIntent(Intent intent) {  
  25.         String url = intent.getStringExtra("url");  
  26.         pool.execute(new DownloadTask(url));  
  27.     }  
  28.   
  29.     @Override  
  30.     public void onDestroy() {  
  31.         super.onDestroy();  
  32.         pool.shutdown();  
  33.     }  
  34.       
  35.     private class DownloadTask implements Runnable {  
  36.           
  37.         private final String url;  
  38.           
  39.         public DownloadTask(String url) {  
  40.             this.url = url;  
  41.         }  
  42.   
  43.         @Override  
  44.         public void run() {  
  45.             // TODO 此處省略具體實現  
  46.         }  
  47.           
  48.     }  
  49.   
  50. }  
0 0
原创粉丝点击