您的位置:首页 > 其它

IntentService 的使用

2015-09-08 14:03 561 查看
英文原文:http://developer.android.com/reference/android/app/IntentService.html

参照文章:http://android.tgbus.com/Android/tutorial/201106/355229.shtml

 IntentService是Service类的子类,用来处理异步请求。客户端可以通过startService(Intent)方法传递请求给IntentService。IntentService在onCreate()函数中通过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
IBinderonBind(Intent intent)
Unless you provide binding for your service, you don't need to implement this method, because the default implementation returns null.
voidonCreate()
Called by the system when the service is first created.
voidonDestroy()
Called by the system to notify a Service that it is no longer used and is being removed.
voidonStart(Intent intent,
int startId)
This method is deprecated. Implement
onStartCommand(Intent,
int, int)
instead.
intonStartCommand(Intent intent,
int flags, int startId)
You should not override this method for your IntentService.
voidsetIntentRedelivery(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 voidonHandleIntent(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文件
<pre style="background-color:#2b2b2b;color:#a9b7c6;font-family:'Consolas';font-size:12.0pt;"><span style="color:#cc7832;">public class </span>MyIntentService <span style="color:#cc7832;">extends </span>IntentService {
<span style="color:#cc7832;">final static </span>String <span style="color:#9876aa;"><em>TAG</em></span>=<span style="color:#6a8759;">"lwb"</span><span style="color:#cc7832;">;
</span><span style="color:#cc7832;">    </span><span style="color:#629755;"><em>/**
</em></span><span style="color:#629755;"><em>     * Creates an IntentService.  Invoked by your subclass's constructor.
</em></span><span style="color:#629755;"><em>     *
</em></span><span style="color:#629755;"><em>     * </em></span><span style="color:#629755;"><strong><em>@param </em></strong></span><span style="color:#8a653b;"><em>name </em></span><span style="color:#629755;"><em>Used to name the worker thread, important only for debugging.
</em></span><span style="color:#629755;"><em>     */
</em></span><span style="color:#629755;"><em>    </em></span><span style="color:#cc7832;">public </span>MyIntentService()
{
<span style="color:#cc7832;">super</span>(<span style="color:#6a8759;">"girl"</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        </span>Log.<span style="font-style:italic;">i</span>(<span style="color:#9876aa;"><em>TAG</em></span><span style="color:#cc7832;">,this</span>+<span style="color:#6a8759;">" is constructed"</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">    </span>}
<span style="color:#808080;">//    public MyIntentService(String name) {
</span><span style="color:#808080;">//        super(name);
</span><span style="color:#808080;">//        Log.i(TAG,this+" is constructed");
</span><span style="color:#808080;">//    }
</span><span style="color:#808080;">
</span><span style="color:#808080;">    </span><span style="color:#bbb529;">@Override
</span><span style="color:#bbb529;">    </span><span style="color:#cc7832;">protected void </span><span style="color:#ffc66d;">onHandleIntent</span>(Intent intent) {
Log.<span style="font-style:italic;">i</span>(<span style="color:#9876aa;"><em>TAG</em></span><span style="color:#cc7832;">, </span><span style="color:#6a8759;">"begin onHandleIntent() in " </span>+ <span style="color:#cc7832;">this</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        try </span>{
Thread.<span style="font-style:italic;">sleep</span>(<span style="color:#6897bb;">10</span>*<span style="color:#6897bb;">1000</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        </span>} <span style="color:#cc7832;">catch </span>(InterruptedException e) {
e.printStackTrace()<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        </span>}
Log.<span style="font-style:italic;">i</span>(<span style="color:#9876aa;"><em>TAG</em></span><span style="color:#cc7832;">, </span><span style="color:#6a8759;">"current threadID is " </span>+Thread.<span style="font-style:italic;">currentThread</span>().getId())<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        </span>Log.<span style="font-style:italic;">i</span>(<span style="color:#9876aa;"><em>TAG</em></span><span style="color:#cc7832;">,</span><span style="color:#6a8759;">"end onHandleIntent() in "</span>+<span style="color:#cc7832;">this</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">    </span>}

<span style="color:#bbb529;">@Override
</span><span style="color:#bbb529;">    </span><span style="color:#cc7832;">public void </span><span style="color:#ffc66d;">onDestroy</span>() {
<span style="color:#cc7832;">super</span>.onDestroy()<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">        </span>Log.<span style="font-style:italic;">i</span>(<span style="color:#9876aa;"><em>TAG</em></span><span style="color:#cc7832;">,this</span>+<span style="color:#6a8759;">" is destroy"</span>)<span style="color:#cc7832;">;
</span><span style="color:#cc7832;">    </span>}
}



启动MyIntentServic的代码片段
 Intent intent=new Intent(this,MyIntentService.class);
   startService(intent);
   startService(intent);
   startService(intent);

AndroidManifest.xml文件代码片段
<service android:name=".MyIntentService" />

运行结果 第一次点一下等待结束后点好多下

09-08 03:51:30.226 4504-4504/intentservice.example.com.intentservie I/lwb﹕
intentservice.example.com.intentservie.MyIntentService@fef7afb is constructed

09-08 03:51:30.229 4504-4585/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:51:40.229 4504-4585/intentservice.example.com.intentservie I/lwb﹕
current threadID is 181

09-08 03:51:40.229 4504-4585/intentservice.example.com.intentservie I/lwb﹕ end onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:51:40.230 4504-4585/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:51:50.231 4504-4585/intentservice.example.com.intentservie I/lwb﹕ current threadID is 181

09-08 03:51:50.231 4504-4585/intentservice.example.com.intentservie I/lwb﹕ end onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:51:50.232 4504-4585/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:52:00.233 4504-4585/intentservice.example.com.intentservie I/lwb﹕ current threadID is 181

09-08 03:52:00.233 4504-4585/intentservice.example.com.intentservie I/lwb﹕ end onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@fef7afb

09-08 03:52:00.234 4504-4504/intentservice.example.com.intentservie I/lwb﹕
intentservice.example.com.intentservie.MyIntentService@fef7afb is destroy

09-08 03:52:07.025 4504-4504/intentservice.example.com.intentservie I/lwb﹕ intentservice.example.com.intentservie.MyIntentService@35e68571 is constructed

09-08 03:52:07.032 4504-4845/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@35e68571

09-08 03:52:17.032 4504-4845/intentservice.example.com.intentservie I/lwb﹕ current threadID is
182

09-08 03:52:17.032 4504-4845/intentservice.example.com.intentservie I/lwb﹕ end onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@35e68571

09-08 03:52:17.033 4504-4845/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@35e68571

09-08 03:52:27.033 4504-4845/intentservice.example.com.intentservie I/lwb﹕ current threadID is
182

09-08 03:52:27.033 4504-4845/intentservice.example.com.intentservie I/lwb﹕ end onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@35e68571

09-08 03:52:27.034 4504-4845/intentservice.example.com.intentservie I/lwb﹕ begin onHandleIntent() in intentservice.example.com.intentservie.MyIntentService@35e68571

09-08 03:52:37.034 4504-4845/intentservice.example.com.intentservie I/lwb﹕ current threadID is 182

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;

public abstract class IntentService extends Service {
    private volatile Looper mServiceLooper;
    private volatile ServiceHandler mServiceHandler;
    private String mName;
    private boolean mRedelivery;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            onHandleIntent((Intent)msg.obj);
            stopSelf(msg.arg1);
        }
    }

    public IntentService(String name) {
        super();
        mName = name;
    }

    public void setIntentRedelivery(boolean enabled) {
        mRedelivery = enabled;
    }

    @Override
    public void 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 = new HandlerThread("IntentService[" + mName + "]");
        thread.start();

        mServiceLooper = thread.getLooper();
        mServiceHandler = new ServiceHandler(mServiceLooper);
    }

    @Override
    public void 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
    public int onStartCommand(Intent intent, int flags, int startId) {
        onStart(intent, startId);
        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        mServiceLooper.quit();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

   protected abstract void onHandleIntent(Intent intent);
}


结束!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: