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" />

  • 相关阅读:
    P3121 [USACO15FEB]审查(黄金)Censoring (Gold)
    P3389 【模板】高斯消元法
    P2260 [清华集训2012]模积和
    【Codevs1237&网络流24题】餐巾计划(费用流)
    【POJ3680】Intervals(费用流)
    【BZOJ1070】修车(费用流)
    【BZOJ1834】network 网络扩容(最大流,费用流)
    【POJ1149&BZOJ1280】PIGS(最大流)
    【BZOJ2127】happiness(最小割)
    【BZOJ3894】文理分科(最小割)
  • 原文地址:https://www.cnblogs.com/yaya-Android/p/4099036.html
Copyright © 2011-2022 走看看