Android Service之串行化Service:IntentService(系列3)


之前写了一系列的文章关于Android Service。
(文章1)《Android Service简介(系列1)》文章链接地址:http://blog.csdn.net/zhangphil/article/details/49373939
(文章2)《Android Activity与Service数据交互:Binder、bindService(系列2)》文章链接地址:http://blog.csdn.net/zhangphil/article/details/49385005

文章1简介了如何使用Android Service。文章2简介了出于前台的Android Activity与后台的Service数据交互。
Android最基础的类Service,提供了通常所需的后台任务处理框架。上层处于前台的Activity通过startService启动后台的Service,然后Service进入onStartCommand做耗时任务。这里面潜在有一个问题,假设Activity里面如果不停的startService启动后台的Service,那么将导致onStartCommand不断的反复调用。这意味着,假如代码中这个Service里面的onStartCommand代码块涉及到并发、多线程时候,就要非常小心处理这种多任务情况。可事实上这种多线程任务在Service里面编程设计实现起来比较复杂和琐碎,好在Android体系架构中为了处理这种开发场景,提供了IntentService。
IntentService也是一个Android Service,IntentService在类层次结构上继承自Service。但IntentService与Service有很大不同。
IntentService是串行化处理后台的Service任务的。Service可以在onStartCommand设计复杂的多线程编程模型。然而IntentService已经将此onStartCommand重载,并引入onHandleIntent,开发者不用关心onStartCommand的任务传导给onHandleIntent的内部实现机制。开发者只需要专心在onHandleIntent里面写串行化的任务逻辑代码即可。开发者该怎么简单的理解IntentService呢?可以这么简单的认为IntentService的编程模型:
(1)当上层代码(通常也就是前台的Activity通过startService启动IntentService)启动IntentService后,IntentService将进入onHandleIntent(不用关心onStartCommand是如何维护任务队列和派发任务的),由于Android系统设计时候已经将onHandleIntent线程化处理,所以可以随意的在onHandleIntent里面做大量耗时操作。
(2)要注意,虽然可以通过startService反复启动IntentService,但是在IntentService中,这些任务将排成一个FIFO的任务队列,依次顺序执行,而不是并发同时执行这些任务。可以startService Intent A,B,C,D,E,,,,但只会串行的顺序执行A,B,C,D,E,,,,。只有在前一个任务完成后才会接着顺序执行下一个任务。换一种理解方式,可以认为同时为每个startService运行了多个线程onHandleIntent,但这些线程只会是FIFO顺序执行。这不同于Service,如果是Service,那么将在onStartCommand并发执行。
(3)虽然可以在上层Activity中反复多次执行startService启动IntentService从而进入onHandleIntent执行后台任务,但只需要调用一次stopService,就可以停止所有IntentService队列中的onHandleIntent,但有一点:如果在调用stopService时候,其中有一个onHandleIntent正在处理还尚未完成,那么将此onHandleIntent不受stopService影响直到处理完成。
给出测试代码。
IntentService的类:

package zhangphil.service;import android.app.IntentService;import android.content.Intent;import android.util.Log;public class MyService extends IntentService {public MyService() {super("MyAppService");}/* * 不要在IntentService里面画蛇添足重载onCreate() 否则将会引起代码崩溃! *  * @Override public void onCreate(){ super.onCreate(); } *//* * 可以不用关心onStartCommand onStartCommand将会把intent串行派发到onHandleIntent里面顺序线程化执行 */@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.d(this.getClass().getName(), "startId:" + startId);return super.onStartCommand(intent, flags, startId);}// onHandleIntent已经线程化,可以在这里面做耗时操作。@Overrideprotected void onHandleIntent(Intent intent) {Log.d(this.getClass().getName(), "onHandleIntent");try {myLongTimeTask();} catch (InterruptedException e) {e.printStackTrace();}}private void myLongTimeTask() throws InterruptedException {for (int i = 0; i < 5; i++) {Log.d(this.getClass().getName(), "i:" + i);Thread.sleep(2000);}}}


测试的Activity MainActivity.java:

package zhangphil.service;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button start = (Button) findViewById(R.id.start);start.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {startMyAppService();}});Button stop = (Button) findViewById(R.id.stop);stop.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {stopMyAppService();}});}private void startMyAppService() {startService(new Intent(this, MyService.class));}private void stopMyAppService() {Intent intent = new Intent(this, MyService.class);boolean bool = stopService(intent);}}



MainActivity.java需要的布局文件activity_main.xml文件提供两个按钮,一个用于启动IntentService的start;另外一个是关闭IntentService的stop:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="zhangphil.service.MainActivity" >    <Button        android:id="@+id/start"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开始" />      <Button        android:id="@+id/stop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="停止" /></LinearLayout>

更多相关文章

  1. 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
  2. 如何在后台运行Linux命令?
  3. Android(安卓)Activity 之间切换的各种效果
  4. Android出现java.lang.RuntimeException: Can‘t toast on a thr
  5. C++调用Android函数弹出一个提示框中出现的问题总结
  6. Android未调用Looper.prepare()-Can't create handler inside th
  7. Android(安卓)- Binder驱动
  8. Android(安卓)Audio System 之二: AudioFlinger
  9. Android如何设置App字体大小不跟随系统字体调整而变化

随机推荐

  1. 帮助你快速使用 Android 的 LiveData 与
  2. 在Android studio中保存keystore
  3. [置顶] Android中资源文件的详解和androi
  4. android 学习文章收藏(链接)
  5. Android(安卓)fragment中弹出的dialogfra
  6. 进阶准备
  7. android 一
  8. android 2.2 apidemos 赏析笔记
  9. Android_使用StrictMode 调试开发
  10. Android Environment 的作用以及常用的方