IntentService介绍及使用

IntentService是一个通过 Context.startService(Intent)启动可以处理异步请求的Service,使用时你只需要继承IntentService和重写其中的 onHandleIntent(Intent)方法接收一个Intent对象,在适当的时候会停止自己(一般在工作完成的时候). 所有的请求的处理都在一个工作线程中完成,它们会交替执行(但不会阻塞主线程的执行),一次只能执行一个请求.

下面是要分析的源码:
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); 
                } 

        }
从源码可以分析出:
IntentService 实际上是Looper,Handler,Service 的集合体,他不仅有服务的功能,还有处理和循环消息的功能.

下面是onCreate()的源码:
        @Override 
         public  void onCreate() { 
                 super.onCreate(); 

                HandlerThread thread =  new HandlerThread( "IntentService[" + mName +  "]"); 
                thread.start(); 

                mServiceLooper = thread.getLooper(); 
                mServiceHandler =  new ServiceHandler(mServiceLooper); 
        }
分析:IntentService创建时就会创建Handler线程(HandlerThread)并且启动,然后再得到当前线程的Looper对象来初始化IntentService的mServiceLooper,接着创建mServicehandler对象.

下面是onStart()的源码:
        @Override 
         public  void onStart(Intent intent,  int startId) { 
                Message msg = mServiceHandler.obtainMessage(); 
                msg.arg1 = startId; 
                msg.obj = intent; 

                mServiceHandler.sendMessage(msg); 
        }
分析:当你启动IntentService的时候,就会产生一条附带startId和Intent的Message并发送到MessageQueue中,接下来Looper发现MessageQueue中有Message的时候,就会停止Handler处理消息,接下来处理的代码如下:
        @Override 
         public  void handleMessage(Message msg) { 
                        onHandleIntent((Intent)msg.obj); 
                        stopSelf(msg.arg1); 
        }
接着调用 onHandleIntent((Intent)msg.obj),这是一个抽象的方法,其实就是我们要重写实现的方法,我们可以在这个方法里面处理我们的工作.当任务完成时就会调用stopSelf(msg.arg1)这个方法来结束指定的工作.

当所有的工作执行完后:就会执行onDestroy方法,源码如下:
        @Override 
         public  void onDestroy() { 
                mServiceLooper.quit(); 
        }
服务结束后调用这个方法 mServiceLooper.quit()使looper停下来.

通过对源码的分析得出:
    这是一个基于消息的服务,每次启动该服务并不是马上处理你的工作,而是首先会创建对应的Looper,Handler并且在MessageQueue中添加的附带客户Intent的Message对象,当Looper发现有Message的时候接着得到Intent对象通过在onHandleIntent((Intent)msg.obj)中调用你的处理程序.处理完后即会停止自己的服务.意思是Intent的生命周期跟你的处理的任务是一致的.所以这个类用下载任务中非常好,下载任务结束后服务自身就会结束退出.

下面通过一个小例子说明。
1、创建一个Activity,添加两个按钮
package com.example.hornsey.myapplication.IntentServiceDemo;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.example.hornsey.myapplication.R;

public class ISDemoActivity extends AppCompatActivity {

    private static final String ACTION_FOO = "com.example.hornsey.myapplication.IntentServiceDemo.action.FOO";
    private static final String ACTION_BAZ = "com.example.hornsey.myapplication.IntentServiceDemo.action.BAZ";

    private static final String EXTRA_PARAM1 = "Name";
    private static final String EXTRA_PARAM2 = "Question";
    private static final String EXTRA_PARAM3 = "Answer";

    private static Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_isdemo);

        context = ISDemoActivity.this;

        findViewById(R.id.btn_action1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActionFoo(context,"Jack","How are you?");
            }
        });

        findViewById(R.id.btn_action2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActionBaz(context,"Tom","Fine!");
            }
        });
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM3, param2);
        context.startService(intent);
    }
}
 
2、定义一个继承自IntentService的Service
package com.example.hornsey.myapplication.IntentServiceDemo;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import java.util.concurrent.TimeUnit;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * helper methods.
 */
public class MyIntentService extends IntentService {
    private static final String TAG = "MyIntentService";
    private static final String ACTION_FOO = "com.example.hornsey.myapplication.IntentServiceDemo.action.FOO";
    private static final String ACTION_BAZ = "com.example.hornsey.myapplication.IntentServiceDemo.action.BAZ";

    private static final String EXTRA_PARAM1 = "Name";
    private static final String EXTRA_PARAM2 = "Question";
    private static final String EXTRA_PARAM3 = "Answer";

    public MyIntentService() {
        super("MyIntentService");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM3);
                handleActionBaz(param1, param2);
            }
        }
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        Log.d(TAG, "handleActionFoo." + param1 + " : " + param2);
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        Log.d(TAG, "handleActionBaz." + param1 + " : " + param2);
    }

    public MyIntentService(String name) {
        super(name);
        Log.d(TAG, "MyIntentService: ");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return super.onBind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy: ");
        super.onDestroy();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.d(TAG, "onStart: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }
}

3、在Manifest.xml中声明
<activity
            android:name=".IntentServiceDemo.ISDemoActivity"
            android:label="@string/title_activity_isdemo"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".IntentServiceDemo.MyIntentService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.example.hornsey.myapplication.IntentServiceDemo.action.FOO" />
                <action android:name="com.example.hornsey.myapplication.IntentServiceDemo.action.BAZ" />
            </intent-filter>
        </service>

4、运行结果如下:
02-26 11:10:07.635 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onCreate: 
02-26 11:10:07.635 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStartCommand: 
02-26 11:10:07.635 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStart: 
02-26 11:10:07.645 6624-7217/com.example.hornsey.myapplication D/MyIntentService: handleActionFoo.Jack : How are you?
02-26 11:10:09.185 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStartCommand: 
02-26 11:10:09.185 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStart: 
02-26 11:10:12.645 6624-7217/com.example.hornsey.myapplication D/MyIntentService: handleActionBaz.Tom : Fine!
02-26 11:10:12.645 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onDestroy: 

02-26 11:10:33.855 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onCreate: 
02-26 11:10:33.855 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStartCommand: 
02-26 11:10:33.855 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStart: 
02-26 11:10:33.855 6624-7668/com.example.hornsey.myapplication D/MyIntentService: handleActionFoo.Jack : How are you?
02-26 11:10:38.865 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onDestroy: 

02-26 11:10:41.915 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onCreate: 
02-26 11:10:41.915 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStartCommand: 
02-26 11:10:41.915 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onStart: 
02-26 11:10:41.925 6624-7790/com.example.hornsey.myapplication D/MyIntentService: handleActionBaz.Tom : Fine!
02-26 11:10:41.925 6624-6624/com.example.hornsey.myapplication D/MyIntentService: onDestroy: 


因为在第一个任务处理过程中,我让服务sleep了5秒,所以第一次两个按钮点击相差2秒时,service只start了一次,当第二个按钮点击启动service时,service已经启动,只是把任务加入处理队列。第二次点击两个按钮相差8秒,所以第一个任务处理完毕后,service已经destroy,当点击第二个按钮时,service又重新启动,处理完任务后再次关闭。


参考:
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值