码迷,mamicode.com
首页 > 其他好文 > 详细

IntentService简介

时间:2018-12-20 14:19:26      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:request   VID   most   const   creates   函数   tor   ring   mes   

 IntentService是Service类的子类,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentServiceIntentServiceonCreate()函数中通过HandlerThread单独开启一个线程来处理所有Intent请求对象(通过startService的方式发送过来的)所对应的任务,这样以免事务处理阻塞主线程。执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,则自动停止Service;否则执行下一个Intent请求所对应的任务
  IntentService在处理事务时,还是采用的Handler方式,创建一个名叫ServiceHandler的内部Handler,并把它直接绑定到HandlerThread所对应的子线程。 ServiceHandler把处理一个intent所对应的事务都封装到叫做onHandleIntent的虚函数;因此我们直接实现虚函数onHandleIntent,再在里面根据Intent的不同进行不同的事务处理就可以了。
另外,IntentService默认实现了Onbind()方法,返回值为null。
  使用IntentService需要两个步骤:
  1、写构造函数
  2实现虚函数onHandleIntent,并在里面根据Intent的不同进行不同的事务处理就可以了。
好处:处理异步请求的时候可以减少写代码的工作量,比较轻松地实现项目的需求
注意IntentService的构造函数一定是参数为空的构造函数,然后再在其中调用super("name")这种形式的构造函数。
因为Service的实例化是系统来完成的,而且系统是用参数为空的构造函数实例化Service的
关于Handler和Service的更多知识请阅读《Looper和Handler》,《关于Handler技术》,《Service简介》,《AIDL和Service实现两进程通信
Public Constructors
  IntentService(String name)
Creates an IntentService.
Public Methods
IBinder onBind(Intent intent)
Unless you provide binding for your service, you don‘t need to implement this method, because the default implementation returns null.
void onCreate()
Called by the system when the service is first created.
void onDestroy()
Called by the system to notify a Service that it is no longer used and is being removed.
void onStart(Intent intent, int startId)
This method is deprecated. Implement onStartCommand(Intent, int, int) instead.
int onStartCommand(Intent intent, int flags, int startId)
You should not override this method for your IntentService.
void setIntentRedelivery(boolean enabled)
Sets intent redelivery preferences.

If enabled is true, onStartCommand(Intent, int, int) will return START_REDELIVER_INTENT, so if this process dies before onHandleIntent(Intent)returns, the process will be restarted and the intent redelivered. If multiple Intents have been sent, only the most recent one is guaranteed to be redelivered.

If enabled is false (the default), onStartCommand(Intent, int, int) will return START_NOT_STICKY, and if the process dies, the Intent dies along with it.

设置为true时,onStartCommand返回START_REDELIVER_INTENT,否则返回START_NOT_STICKY
关于此的更多内容请参考《Service简介
Protected Methods
abstract void onHandleIntent(Intent intent)
This method is invoked on the worker thread with a request to process.
This method is invoked on the worker thread with a request to process. Only one Intent is processed at a time, but the processing happens on a worker thread that runs independently from other application logic. So, if this code takes a long time, it will hold up other requests to the same IntentService, but it will not hold up anything else. When all requests have been handled, the IntentService stops itself, so you should not call stopSelf().
该函数用于针对Intent的不同进行不同的事务处理就可以了.执行完所一个Intent请求对象所对应的工作之后,如果没有新的Intent请求达到,
则自动停止Service;否则ServiceHandler会取得下一个Intent请求传人该函数来处理其所对应的任务。
 

实例1
MyIntentService.java文件

 

package com.lenovo.robin.test;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
 
publicclassMyIntentServiceextendsIntentService{
finalstaticString TAG="robin";
publicMyIntentService(){
super("com.lenovo.robin.test.MyIntentService");
Log.i(TAG,this+" is constructed");
}
@Override
protectedvoid 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);
}
publicvoid onDestroy()
{
super.onDestroy();
Log.i(TAG,this+" is destroy");
}
}

 

启动MyIntentServic的代码片段

 

Intent intent=newIntent(this,MyIntentService.class);
startService(intent);
startService(intent);
startService(intent);

 

AndroidManifest.xml文件代码片段

<serviceandroid:name=".MyIntentService"/>

运行结果
09-14 22:23:34.730: I/robin(30943): com.lenovo.robin.test.MyIntentService@40541370 is constructed
09-14 22:23:34.730: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:44.730: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:44.730: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:54.740: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:23:54.740: I/robin(30943): begin onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:24:04.739: I/robin(30943): end onHandleIntent() in com.lenovo.robin.test.MyIntentService@40541370
09-14 22:24:04.739: I/robin(30943): com.lenovo.robin.test.MyIntentService@40541370 is destroy
IntentService源码

 

package android.app;
 
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
 
publicabstractclassIntentServiceextendsService{
    privatevolatileLooper mServiceLooper;
    privatevolatileServiceHandler mServiceHandler;
    privateString mName;
    privateboolean mRedelivery;
 
    privatefinalclassServiceHandlerextendsHandler{
        publicServiceHandler(Looper looper){
            super(looper);
        }
 
        @Override
        publicvoid handleMessage(Message msg){
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }
 
    publicIntentService(String name){
        super();
        mName = name;
    }
 
    publicvoid setIntentRedelivery(boolean enabled){
        mRedelivery = enabled;
    }
 
    @Override
    publicvoid onCreate(){
        // TODO: It would be nice to have an option to hold a partial wakelock
        // during processing, and to have a static startService(Context, Intent)
        // method that would launch the service & hand off a wakelock.
 
        super.onCreate();
        HandlerThread thread =newHandlerThread("IntentService["+ mName +"]");
        thread.start();
 
        mServiceLooper = thread.getLooper();
        mServiceHandler =newServiceHandler(mServiceLooper);
    }
 
    @Override
    publicvoid onStart(Intent intent,int startId){
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = intent;
        mServiceHandler.sendMessage(msg);
    }
 
    /**
     * You should not override this method for your IntentService. Instead,
     * override {@link #onHandleIntent}, which the system calls when the IntentService
     * receives a start request.
     * @see android.app.Service#onStartCommand
     */
    @Override
    publicint onStartCommand(Intent intent,int flags,int startId){
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }
 
    @Override
    publicvoid onDestroy(){
        mServiceLooper.quit();
    }
    @Override
    publicIBinder onBind(Intent intent){
        returnnull;
    }
 
  protectedabstractvoid onHandleIntent(Intent intent);
}

 

 
结束!

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!希望你也加入到我们人工智能的队伍中来!https://www.cnblogs.com/captainbed

IntentService简介

标签:request   VID   most   const   creates   函数   tor   ring   mes   

原文地址:https://www.cnblogs.com/siwnchh/p/10148387.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!