Android Service介绍(二)

    前一篇文章介绍了Service基本的知识,如果还不太了解Service的基本知识请参考https://blog.csdn.net/hickey96/article/details/79992146。这篇文章里要介绍Service其它方面的一些知识。

        这篇文章介绍下IntentService相关的知识。

 一、简介

       IntentService是继承并处理异步请求的一个类客户端通过startService(Intent)调用发送请求;该服务是根据需要启动的,使用一个工作线程来处理每个意图,当任务执行完后,IntentService会自动停止

       这种“工作队列处理器”模式通常用于从应用程序的主线程中卸载任务。 IntentService类的存在是为了简化这种模式。 要使用它,扩展IntentService并实现onHandleIntent(Intent)。 IntentService将收到Intents,启动一个工作线程,并在适当的时候停止服务。
       所有请求都在单个工作线程处理 - 它们可能需要很长的时间(并且不会阻止应用程序的主循环),但是一次只会处理一个请求。 
     

二、使用场景

     在Android开发中,我们或许会碰到这么一种需求,一项任务分成几个子任务,子任务按顺序先后执行,子任务全部执行完后,这项任务才算成功。那么,利用几个子线程顺序执行是可以达到这个目的的,但是每个线程必须手动控制,而且得在一个子线程执行完后,再开启另一个子线程。或者,全部放到一个线程中让其顺序执行。这样都可以做到,但是,如果这是一个后台任务,就得放到Service里面,由于Service和Activity是同级的,所以,要执行耗时任务,就得在Service里面开子线程来执行。那么,IntentService,就非常适合用来处理这个过程。

三、用法

1.新建一个类,继承自IntentService,示例如下:

 
public class MyIntentService extends IntentService {
    public static final String TAG = "MyIntentService";
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "com.jiusi.equiview.action.FOO";
    private static final String ACTION_BAZ = "com.jiusi.equiview.action.BAZ";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "com.jiusi.equiview.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.jiusi.equiview.extra.PARAM2";

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

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

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"--------onCreate--------" + " Thread = "+ Thread.currentThread().getName());
    }

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

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

    @Override
    public void setIntentRedelivery(boolean enabled) {
        super.setIntentRedelivery(enabled);
        Log.e(TAG,"--------setIntentRedelivery--------");
    }

    /**
     * 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
     */
    // TODO: Customize helper method
    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
     */
    // TODO: Customize helper method
    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_PARAM2, param2);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            //Intent是从Activity发过来的,携带识别参数,根据参数不同执行不同的任务
            String action = intent.getExtras().getString("param");
            if (action.equals("Operation1")) {
                Log.e(TAG,"--------Operation1--------" + "Thread = " + Thread.currentThread().getName());
            }else if (action.equals("Operation2")) {
                Log.e(TAG,"--------Operation2--------"+ "Thread = " + Thread.currentThread().getName());
            }

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

2.在AndroidManifest.xml配置服务

<service
    android:name=".MyIntentService"
    android:exported="false" />

3.调用,本示例中是在Activity中调用的

public class MyActivity extends Activity {

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

        //可以启动多次,每启动一次,就会新建一个work thread,但IntentService的实例始终只有一个
        //Operation 1
        Intent startServiceIntent = new Intent(this,MyIntentService.class);
        Bundle bundle = new Bundle();
        bundle.putString("param", "Operation1");
        startServiceIntent.putExtras(bundle);
        startService(startServiceIntent);

        //Operation 2
        Intent startServiceIntent2 = new Intent(this,MyIntentService.class);
        Bundle bundle2 = new Bundle();
        bundle2.putString("param", "Operation2");
        startServiceIntent2.putExtras(bundle2);
        startService(startServiceIntent2);
    }

}

然后我们运行的结果:

05-10 18:18:54.724 16551-16551/com.jiusi.equiview E/MyIntentService: --------onCreate-------- Thread = main

    --------onStartCommand--------
    --------onStart--------
    --------onStartCommand--------
    --------onStart--------
05-10 18:18:54.724 16551-16577/com.jiusi.equiview E/MyIntentService: --------Operation1--------Thread = IntentService[MyIntentService]
05-10 18:18:56.734 16551-16577/com.jiusi.equiview E/MyIntentService: --------Operation2--------Thread = IntentService[MyIntentService]

05-10 18:18:58.734 16551-16551/com.jiusi.equiview E/MyIntentService: --------onDestroy--------

       从结果可以看到,onCreate方法只执行了一次,而onStartCommand和onStart方法执行了两次,并且开启了Work Thread,这就证实了之前所说的,启动多次,但IntentService的实例只有一个,这跟传统的Service是一样的。Operation1也是先于Operation2打印,并且我让两个操作间停顿了2s,最后是onDestroy销毁了IntentService。

       这就是IntentService,一个方便我们处理业务流程的类,它是一个Service,但是比Service更智能。希望通过本文大家能掌握IntentService,有错误之处欢迎指正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值