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

  • 相关阅读:
    EfCore基本用法
    C#笔试题目总结
    LINQ
    markdown 语法
    打造一款 刷Java 知识的小程序(二)
    为了考PMP,我做了一个刷题小程序
    30分钟全面解析-SQL事务+隔离级别+阻塞+死锁
    反制面试官 | 14张原理图 | 再也不怕被问 volatile!
    50+道大厂JVM面试题 + 11张思维导图就是让你懂JVM~
    【从零开始用Swift开发一个iOS应用(仿微博)】开篇-1. demo上手体验
  • 原文地址:https://www.cnblogs.com/yaya-Android/p/4099036.html
Copyright © 2011-2022 走看看