android中IntentService和Service有什么区别

1.Service不是一个单独的进程 ,它和应用程序在同一个进程中。

2.Service不是一个线程,所以我们应该避免在Service里面进行耗时的操作.

IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。

例子

1.定义普通Service
/**
 * 普通的Service
 *
 *  @author  Administrator
 *
 */
public  class  MyService  extends  Service {

      @Override
      public  IBinder onBind(Intent intent) {
             return  null ;
     }

      @Override
      public  int  onStartCommand(Intent intent,  int  flags,  int  startId) {
           System.  out .println(  "开始睡!" );
           SystemClock. sleep(20000);
           System.  out .println(  "停止睡" );
             return  super .onStartCommand(intent, flags, startId);

     }

}

2.定义IntentService


/**
 * IntentService
 *
 *  @author  Administrator
 *
 */
public  class  MyIntentService  extends  IntentService {

      // IntentService必须提供一个无参的构造,不然会发生异常
      public  MyIntentService() {
             super (  "testIntentService" );
     }

      @Override
      protected  void  onHandleIntent(Intent intent) {
           System.  out .println(  "开始睡!" );
           SystemClock. sleep(20000);
           System.  out .println(  "停止睡" );
     }

}

3.定义测试类:

public  class  MainActivity  extends  Activity {

      @Override
      protected  void  onCreate(Bundle savedInstanceState) {
             super .onCreate(savedInstanceState);
           setContentView(R.layout.  activity_main );
     }

      // IntentService
      public  void  intentService(View view) {
           Intent intentService =  new  Intent(  this , MyIntentService. class );
           startService(intentService);
     }

      // 普通Service
      public  void  Service(View view) {
           Intent service =  new  Intent(  this , MyService.  class );
           Intent service1 =  new  Intent(  this , MyService.  class );
           Intent service2 =  new  Intent(  this , MyService.  class );
           startService(service);
           startService(service1);
           startService(service2);
     }

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值