zoukankan      html  css  js  c++  java
  • IntentService简介

    IntentService简介

    http://developer.android.com/reference/android/app/IntentService.html
    http://android.tgbus.com/Android/tutorial/201106/355229.shtml
    IntentService在处理事务时,还是采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 
    ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent的虚函数;
    因此我们直接实现虚函数onHandleIntent,再在里面根据Intent的不同进行不同的事务处理就可以了。
    另外,IntentService默认实现了Onbind()方法,返回值为null。
      使用IntentService需要两个步骤:
      1、写构造函数
      2实现虚函数onHandleIntent,并在里面根据Intent的不同进行不同的事务处理就可以了。
    好处:处理异步请求的时候可以减少写代码的工作量,比较轻松地实现项目的需求
    实例1
    MyIntentService.java文件
    package com.lenovo.robin.test;
    import android.app.IntentService;
    import android.content.Intent;
    import android.util.Log;
     
    public class MyIntentService extends IntentService {
    final static String TAG="robin";
    public MyIntentService() {
    super("com.lenovo.robin.test.MyIntentService");
    Log.i(TAG,this+" is constructed");
    }
    @Override
    protected void onHandleIntent(Intent arg0) {
    Log.i(TAG,"begin onHandleIntent() in "+this);
    try {
    Thread.sleep(10*1000);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    Log.i(TAG,"end onHandleIntent() in "+this);
    }
    public void onDestroy()
    {
    super.onDestroy();
    Log.i(TAG,this+" is destroy");
    }
    }
    启动MyIntentServic的代码片段
    Intent intent=new Intent(this,MyIntentService.class);
    startService(intent);
    startService(intent);
    startService(intent);
    AndroidManifest.xml文件代码片段

    <service android:name=".MyIntentService" />

  • 相关阅读:
    Python中循环引用(import)失败的解决方法
    junit中线程需要注意的问题
    python动态绑定属性和方法
    python输出缓冲区的问题
    使用RateLimiter完成简单的大流量限流,抢购秒杀限流
    guava的限流工具RateLimiter使用
    高性能分布式锁-redisson的使用
    正则表达式
    input 标签鼠标放入输入框补全提示
    Google guava工具类的介绍和使用
  • 原文地址:https://www.cnblogs.com/yaya-Android/p/4099036.html
Copyright © 2011-2022 走看看