Android 中的 Service 全面总结

来源:互联网 发布:魔方数据恢复官网 编辑:程序博客网 时间:2024/06/06 02:17

1、Service的种类

  

按运行地点分类:

类别区别 优点缺点  应用本地服务(Local)该服务依附在主进程上, 服务依附在主进程上而不是独立的进程,这样在一定程度上节约了资源,另外Local服务因为是在同一进程因此不需要IPC,也不需要AIDL。相应bindService会方便很多。 主进程被Kill后,服务便会终止。 非常常见的应用如:HTC的音乐播放服务,天天动听音乐播放服务。远程服务(Remote该服务是独立的进程, 服务为独立的进程,对应进程名格式为所在包名加上你指定的android:process字符串。由于是独立的进程,因此在Activity所在进程被Kill的时候,该服务依然在运行,不受其他进程影响,有利于为多个进程提供服务具有较高的灵活性。 该服务是独立的进程,会占用一定资源,并且使用AIDL进行IPC稍微麻烦一点。 一些提供系统服务的Service,这种Service是常驻的。

其实remote服务还是很少见的,并且一般都是系统服务。

  

按运行类型分类:

类别区别应用前台服务会在通知一栏显示 ONGOING 的 Notification,当服务被终止的时候,通知一栏的 Notification 也会消失,这样对于用户有一定的通知作用。常见的如音乐播放服务。后台服务默认的服务即为后台服务,即不会在通知一栏显示 ONGOING 的 Notification。当服务被终止的时候,用户是看不到效果的。某些不需要运行或终止提示的服务,如天气更新,日期同步,邮件同步等。

有同学可能会问,后台服务我们可以自己创建 ONGOING 的 Notification 这样就成为前台服务吗?答案是否定的,前台服务是在做了上述工作之后需要调用 startForeground ( android 2.0 及其以后版本 )或 setForeground (android 2.0 以前的版本)使服务成为 前台服务。这样做的好处在于,当服务被外部强制终止掉的时候,ONGOING 的 Notification 任然会移除掉。

 

按使用方式分类:

类别区别startService 启动的服务主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopServicebindService 启动的服务该方法启动的服务要进行通信。停止服务使用unbindServicestartService 同时也 bindService 启动的服务停止服务应同时使用stepService与unbindService

以上面三种方式启动的服务其生命周期也有区别,将在随后给出。

 

2、Service 与 Thread 的区别

  

很多时候,你可能会问,为什么要用 Service,而不用 Thread 呢,因为用 Thread 是很方便的,比起 Service 也方便多了,下面我详细的来解释一下。

 

1). Thread:Thread 是程序执行的最小单元,它是分配CPU的基本单位。可以用 Thread 来执行一些异步的操作。

2). Service:Service 是android的一种机制,当它运行的时候如果是Local Service,那么对应的 Service 是运行在主进程的 main 线程上的。如:onCreate,onStart 这些函数在被系统调用的时候都是在主进程的 main 线程上运行的。如果是Remote Service,那么对应的 Service 则是运行在独立进程的 main 线程上。因此请不要把 Service 理解成线程,它跟线程半毛钱的关系都没有!

  

既然这样,那么我们为什么要用 Service 呢?其实这跟 android 的系统机制有关,我们先拿 Thread 来说。Thread 的运行是独立于 Activity 的,也就是说当一个 Activity 被 finish 之后,如果你没有主动停止 Thread 或者 Thread 里的 run 方法没有执行完毕的话,Thread 也会一直执行。因此这里会出现一个问题:当 Activity 被 finish 之后,你不再持有该 Thread 的引用。另一方面,你没有办法在不同的 Activity 中对同一 Thread 进行控制。

  

举个例子:如果你的 Thread 需要不停地隔一段时间就要连接服务器做某种同步的话,该 Thread 需要在 Activity 没有start的时候也在运行。这个时候当你 start 一个 Activity 就没有办法在该 Activity 里面控制之前创建的 Thread。因此你便需要创建并启动一个 Service ,在 Service 里面创建、运行并控制该 Thread,这样便解决了该问题(因为任何 Activity 都可以控制同一 Service,而系统也只会创建一个对应 Service 的实例)。

  

因此你可以把 Service 想象成一种消息服务,而你可以在任何有 Context 的地方调用 Context.startService、Context.stopService、Context.bindService,Context.unbindService,来控制它,你也可以在 Service 里注册 BroadcastReceiver,在其他地方通过发送 broadcast 来控制它,当然这些都是 Thread 做不到的。

  

3、Service的生命周期

             两种比较 



onCreate  onStart  onDestroy  onBind 

1). 被启动的服务的生命周期:如果一个Service被某个Activity 调用 Context.startService 方法启动,那么不管是否有Activity使用bindService绑定或unbindService解除绑定到该Service,该Service都在后台运行。如果一个Service被startService 方法多次启动,那么onCreate方法只会调用一次,onStart将会被调用多次(对应调用startService的次数),并且系统只会创建Service的一个实例(因此你应该知道只需要一次stopService调用)。该Service将会一直在后台运行,而不管对应程序的Activity是否在运行,直到被调用stopService,或自身的stopSelf方法。当然如果系统资源不足,android系统也可能结束服务。

 

2). 被绑定的服务的生命周期:如果一个Service被某个Activity 调用 Context.bindService 方法绑定启动,不管调用 bindService 调用几次,onCreate方法都只会调用一次,同时onStart方法始终不会被调用。当连接建立之后,Service将会一直运行,除非调用Context.unbindService 断开连接或者之前调用bindService 的 Context 不存在了(如Activity被finish的时候),系统将会自动停止Service,对应onDestroy将被调用。

 

3). 被启动又被绑定的服务的生命周期:如果一个Service又被启动又被绑定,则该Service将会一直在后台运行。并且不管如何调用,onCreate始终只会调用一次,对应startService调用多少次,Service的onStart便会调用多少次。调用unbindService将不会停止Service,而必须调用 stopService 或 Service的 stopSelf 来停止服务。

 

4). 当服务被停止时清除服务:当一个Service被终止(1、调用stopService;2、调用stopSelf;3、不再有绑定的连接(没有被启动))时,onDestroy方法将会被调用,在这里你应当做一些清除工作,如停止在Service中创建并运行的线程。

 

特别注意:

1、你应当知道在调用 bindService 绑定到Service的时候,你就应当保证在某处调用 unbindService 解除绑定(尽管 Activity 被 finish 的时候绑定会自      动解除,并且Service会自动停止);

2、你应当注意 使用 startService 启动服务之后,一定要使用 stopService停止服务,不管你是否使用bindService; 

3、同时使用 startService 与 bindService 要注意到,Service 的终止,需要unbindService与stopService同时调用,才能终止 Service,不管 startService 与 bindService 的调用顺序,如果先调用 unbindService 此时服务不会自动终止,再调用 stopService 之后服务才会停止,如果先调用 stopService 此时服务也不会终止,而再调用 unbindService 或者 之前调用 bindService 的 Context 不存在了(如Activity 被 finish 的时候)之后服务才会自动停止;

4、当在旋转手机屏幕的时候,当手机屏幕在“横”“竖”变换时,此时如果你的 Activity 如果会自动旋转的话,旋转其实是 Activity 的重新创建,因此旋转之前的使用 bindService 建立的连接便会断开(Context 不存在了),对应服务的生命周期与上述相同。

5、在 sdk 2.0 及其以后的版本中,对应的 onStart 已经被否决变为了 onStartCommand,不过之前的 onStart 任然有效。这意味着,如果你开发的应用程序用的 sdk 为 2.0 及其以后的版本,那么你应当使用 onStartCommand 而不是 onStart。

 

4、startService 启动服务

  

想要用 startService  启动服务,不管Local 还是 Remote 我们需要做的工作都是一样简单。当然要记得在 Androidmanifest.xml 中注册 service。

根据上面的生命周期,我们便会给出 Service 中的代码框架:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.newcj.test;
 
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
 
public class LocalService1extends Service {
 
    /**
     * onBind 是 Service 的虚方法,因此我们不得不实现它。
     * 返回 null,表示客服端不能建立到此服务的连接。
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
     
    @Override
    public void onCreate() {
        super.onCreate();
    }
     
    @Override
    public void onStart(Intent intent,int startId) {
        super.onStart(intent, startId);
    }
     
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
 
}

对应生命周期系统回调函数上面已经说明,在对应地方加上适当的代码即可。下面是启动与停止 Service 的代码:

?
1
2
3
4
5
// 启动一个 Activity
startActivity(new Intent(this, LocalService1.class));
...
// 停止一个 Activity
stopService(new Intent(this, LocalService1.class));

对应的 Intent 为标志服务类的 Intent。


拥有service的进程具有较高的优先级
    官方文档告诉我们,Android系统会尽量保持拥有service的进程运行,只要在该service已经被启动(start)或者客户端连接(bindService)到它。当内存不足时,需要保持,拥有service的进程具有较高的优先级。

1. 如果service正在调用onCreate,onStartCommand或者onDestory方法,那么用于当前service的进程则变为前台进程以避免被killed。

2. 如果当前service已经被启动(start),拥有它的进程则比那些用户可见的进程优先级低一些,但是比那些不可见的进程更重要,这就意味着service一般不会被killed.

3. 如果客户端已经连接到service (bindService),那么拥有Service的进程则拥有最高的优先级,可以认为service是可见的。

4. 如果service可以使用startForeground(int, Notification)方法来将service设置为前台状态,那么系统就认为是对用户可见的,并不会在内存不足时killed。


 

5、Local 与 Remote 服务绑定

 

同样记得在 Androidmanifest.xml 中注册 service

1). Local 服务绑定:Local 服务的绑定较简单,首先在 Service 中我们需要实现 Service 的抽象方法 onBind,并返回一个实现 IBinder 接口的对象。

Service 中的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.newcj.test;
 
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
 
public class LocalServiceextends Service {
 
    /**
     * 在 Local Service 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
     * @author newcj
     */
    public class SimpleBinderextends Binder{
        /**
         * 获取 Service 实例
         * @return
         */
        public LocalService getService(){
            return LocalService.this;
        }
         
        public int add(int a,int b){
            return a + b;
        }
    }
     
    public SimpleBinder sBinder;
     
    @Override
    public void onCreate() {
        super.onCreate();
        // 创建 SimpleBinder
        sBinder = new SimpleBinder();
    }
     
    @Override
    public IBinder onBind(Intent intent) {
        // 返回 SimpleBinder 对象
        return sBinder;
    }
 
}

上面的代码关键之处,在于 onBind(Intent) 这个方法 返回了一个实现了 IBinder 接口的对象,这个对象将用于绑定Service 的 Activity 与 Local Service 通信。下面是 Activity 中的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.newcj.test;
 
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
 
public class Mainextends Activity {
    private final static String TAG = "SERVICE_TEST";
    private ServiceConnection sc;
    private boolean isBind;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sc = new ServiceConnection() {
             
            @Override
            public void onServiceDisconnected(ComponentName name) {
 
            }
             
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                LocalService.SimpleBinder sBinder = (LocalService.SimpleBinder)service;
                Log.v(TAG, "3 + 5 = " + sBinder.add(3,5));
                Log.v(TAG, sBinder.getService().toString());
            }
        };
        findViewById(R.id.btnBind).setOnClickListener(new OnClickListener() {
             
            @Override
            public void onClick(View v) {
                bindService(new Intent(Main.this, LocalService.class), sc, Context.BIND_AUTO_CREATE);
                isBind = true;
            }
        });
        findViewById(R.id.btnUnbind).setOnClickListener(new OnClickListener() {
             
            @Override
            public void onClick(View v) {
                if(isBind){
                    unbindService(sc);
                    isBind = false;
                }
            }
        });
    }
}

在 Activity 中,我们通过 ServiceConnection 接口来取得建立连接 与 连接意外丢失的回调。bindService有三个参数,第一个是用于区分 Service 的Intent 与 startService 中的 Intent 一致,第二个是实现了 ServiceConnection 接口的对象,最后一个是 flag 标志位。有两个flag,BIND_DEBUG_UNBIND 与 BIND_AUTO_CREATE,前者用于调试(详细内容可以查看javadoc 上面描述的很清楚),后者默认使用。unbindService 解除绑定,参数则为之前创建的 ServiceConnection 接口对象。另外,多次调用 unbindService 来释放相同的连接会抛出异常,因此我创建了一个 boolean 变量来判断是否 unbindService 已经被调用过。

运行结果:

 

2). Remote 服务绑定:Remote 的服务绑定由于服务是在另外一个进程,因此需要用到 android 的 IPC 机制。这将又是一个很长的话题,因此,我打算写另外一篇 android 的 IPC 机制分析 ,并在其中进行详述,然后在这里更新链接,敬请关注。

 

特别注意:

1、Service.onBind如果返回null,则调用 bindService 会启动 Service,但不会连接上 Service,因此 ServiceConnection.onServiceConnected 不会被调用,但你任然需要使用 unbindService 函数断开它,这样 Service 才会停止。

 

 6、创建前台服务

  在前台运行Service一个前台的service是被用户强烈关注的从而不会在内存低时被系统杀死.前台service必须在状态栏上提供一个通知,这个通知被放在"正在进行"区域中,这表示这个通知不能被解除,除非服务停止了或者从前台移除了.

 一个从service播放音乐的音乐播放器,应被设置为前台运行,因为用户会明确地注意它的运行.在状态栏中的通知可能会显示当前的歌曲并且允许用户启动一个activity来与音乐播放器交互.

  Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
  System.currentTimeMillis());
  Intent notificationIntent = new Intent(this, ExampleActivity。class);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
  notification.setLatestEventInfo(this, getText(R.string.notification_title),
  getText(R.string.notification_message), pendingIntent);
  startForeground(ONGOING_NOTIFICATION, notification);

要请求你的service运行于前台,调用startForeground().此方法有两个参数:一个整数唯一的标识一个通知,和这个用于状态栏的通知,例如:

要从前台移除service,调用stopForeground().这个方法有boolean型参数,表明是否也从状态栏删除对应的通知.这个方法不会停掉service.然而,如果你停止了正在前台运行的service,这个通知也会被删除.

前台服务的优点上面已经说明,但设置服务为前台服务,我们需要注意在 sdk 2.0 及其以后版本使用的方法是 startForeground 与 stopForeground,之前版本使用的是 setForeground ,因此如果你应用程序的最低运行环境要求是 2.0,那么这里可以直接运用新方法,如果运行环境是2.0以下,那么为了保证向后兼容性,这里必须使用反射技术来调用新方法。

下面是我仿照 ApiDemos 重新敲的代码,对某些地方进行了修改,因此更具有说明性:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.newcj.test;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
 
public class ForegroundServiceextends Service {
 
    private static final Class[] mStartForegroundSignature = new Class[] {
        int.class, Notification.class};
    private static final Class[] mStopForegroundSignature = new Class[] {
        boolean.class};
    private NotificationManager mNM;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];
     
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
     
    @Override
    public void onCreate() {
        super.onCreate();
        mNM = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        try {
            mStartForeground = ForegroundService.class.getMethod("startForeground", mStartForegroundSignature);
            mStopForeground = ForegroundService.class.getMethod("stopForeground", mStopForegroundSignature);
        }catch (NoSuchMethodException e) {
            mStartForeground = mStopForeground =null;
        }
         // 我们并不需要为 notification.flags 设置 FLAG_ONGOING_EVENT,因为
         // 前台服务的 notification.flags 总是默认包含了那个标志位
        Notification notification =new Notification(R.drawable.icon,"Foreground Service Started.",
                System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this,0,
                new Intent(this, Main.class),0);
        notification.setLatestEventInfo(this,"Foreground Service",
                "Foreground Service Started.", contentIntent);
        // 注意使用  startForeground ,id 为 0 将不会显示 notification
        startForegroundCompat(1, notification);
    }
     
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForegroundCompat(1);
    }
     
    // 以兼容性方式开始前台服务
    private void startForegroundCompat(int id, Notification n){
        if(mStartForeground != null){
            mStartForegroundArgs[0] = id;
            mStartForegroundArgs[1] = n;
             
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
            }catch (IllegalArgumentException e) {
                e.printStackTrace();
            }catch (IllegalAccessException e) {
                e.printStackTrace();
            }catch (InvocationTargetException e) {
                e.printStackTrace();
            }
             
            return;
        }
        setForeground(true);
        mNM.notify(id, n);
    }
     
    // 以兼容性方式停止前台服务
    private void stopForegroundCompat(int id){
        if(mStopForeground != null){
            mStopForegroundArgs[0] = Boolean.TRUE;
             
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            }catch (IllegalArgumentException e) {
                e.printStackTrace();
            }catch (IllegalAccessException e) {
                e.printStackTrace();
            }catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return;
        }
         
        //  在 setForeground 之前调用 cancel,因为我们有可能在取消前台服务之后
        //  的那一瞬间被kill掉。这个时候 notification 便永远不会从通知一栏移除
        mNM.cancel(id);
        setForeground(false);
    }
 
}

特别注意:

  1、使用 startForeground ,如果 id 为 0 ,那么 notification 将不会显示。

  

7、在什么情况下使用 startService 或 bindService 或 同时使用startService 和 bindService

  

如果你只是想要启动一个后台服务长期进行某项任务那么使用 startService 便可以了。如果你想要与正在运行的 Service 取得联系,那么有两种方法,一种是使用 broadcast ,另外是使用 bindService ,前者的缺点是如果交流较为频繁,容易造成性能上的问题,并且 BroadcastReceiver 本身执行代码的时间是很短的(也许执行到一半,后面的代码便不会执行),而后者则没有这些问题,因此我们肯定选择使用 bindService(这个时候你便同时在使用 startService 和 bindService 了,这在 Activity 中更新 Service 的某些运行状态是相当有用的)。另外如果你的服务只是公开一个远程接口,供连接上的客服端(android 的 Service 是C/S架构)远程调用执行方法。这个时候你可以不让服务一开始就运行,而只用 bindService ,这样在第一次 bindService 的时候才会创建服务的实例运行它,这会节约很多系统资源,特别是如果你的服务是Remote Service,那么该效果会越明显(当然在 Service 创建的时候会花去一定时间,你应当注意到这点)。

  

 

8、在 AndroidManifest.xml 里 Service 元素的常见选项

android:name  -------------  服务类名

android:label  --------------  服务的名字,如果此项不设置,那么默认显示的服务名则为类名

android:icon  --------------  服务的图标

android:permission  -------  申明此服务的权限,这意味着只有提供了该权限的应用才能控制或连接此服务

android:process  ----------  表示该服务是否运行在另外一个进程,如果设置了此项,那么将会在包名后面加上这段字符串表示另一进程的名字

android:enabled  ----------  如果此项设置为 true,那么 Service 将会默认被系统启动,不设置默认此项为 false

android:exported  ---------  表示该服务是否能够被其他应用程序所控制或连接,不设置默认此项为 false


 9.它被用于监视一个Service是否由于已经运转,如果由于各种原因Service已经被停止了。

这是在重新启动指定Service。
它被用于一个Application中有多个Service。
    public static boolean isServiceExisted(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(Integer.MAX_VALUE);

        if(!(serviceList.size() > 0)) {
            return false;
        }

        for(int i = 0; i < serviceList.size(); i++) {
            RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;

            if(serviceName.getClassName().equals(className)) {
                return true;
            }
        } 
        return false;
    }


10.关于service的几个小问题

1. 如Service的创建都是在新进程创建的么? 

当创建一个Service的时候,默认是在Application的进程里主UI线程创建的,如果你在Service中进行阻塞的操作,会直接阻塞UI线程,可能导致五秒无响应的提醒,所以官方建议是在Service里面创建新的线程来防止阻塞放生。 

2. 如何在新进程里创建Service? 
一般的方法就是在manifast中声明Service的时候,使用process标签,注明所使用的进程,默认使用当前程序主进程: 

Java代码  收藏代码
  1. <service   
  2.     android:name="org.foreal.MusicServiceTest"  
  3.     android:enabled="true"   
  4.     android:process=":music_process"  
  5. ></service>  

其中如果进程的名字时以 ":"开头的,说明进程是当前程序的私有进程,其他程序无法访问,如果是以小写字母开头的进程,说明进程是一个全局的进程,多个程序都可访问此进程,达到多程序共享进程的目的。 

3.如果不用新进程的Service,如何方便的进行一些阻塞操作? 
可以继承IntentService来编写自己的Service,IntentService会自动创建一个worker thread,来进行操作如: 
Java代码  收藏代码
  1. public class MyIntentService extends IntentService {  
  2.       
  3.     private final static String TAG = "MyIntentService";   
  4.   
  5.     public MyIntentService() {  
  6.         super("MyIntentService");  
  7.     }  
  8.   
  9.     @Override  
  10.     protected void onHandleIntent(Intent intent) {  
  11.         Log.i(TAG, "onHandleIntent");  
  12.           
  13.         try {  
  14.             synchronized (this){  
  15.                 wait(3000);  
  16.             }  
  17.             Log.i(TAG, "完成一次");  
  18.         } catch (InterruptedException e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.     }  
  22. }  

其中只需要重写onHandleIntent方法来处理自己的操作就行,其中每一次的操作都会进去队列中,按顺序串行执行。 
其中要注意的是,IntentService在执行完队列中所有操作以后会自动销毁当前Service,也就是说,如果你onHandleIntent中是个非阻塞操作的话,很可能每次调用结束以后Service都被销毁,然后下次在建立新的Service。 
此类可以很方便的完成大多数工作,但是如果要进行并发操作的Service,此类就不适合,应自己实现。 

3. 如何使Service私有? 
如果在Service中声明intent filter,那么其他程序也可以通过你声明的intent filter来访问你的Service,为了避免这种情况,首先你可以去掉intent filter,每次调用Service都使用Intent(Context, Class)的形式,但是,如果喜欢用intent filter的形式,可以使用exported标签,来使Service私有,这样即使定义intent filter,其他程序也无法访问。 

4.如果一个Service在startService以后 又进行了bindService那么他的生命周期是怎样的,stopService能否结束掉Service? 
答案是不能的,如果一个Service进行了bind操作,那么再进行stopService是无法结束掉此Service,知道绑定的Context全部结束,或解除绑定,Service才会被结束。 

5. Service 中Onstart方法中,参数startid是什么意思,又有什么用处? 
因为在使用startService开启一个Service以后,必须手动的关闭Service,所以Service可能自己调用 stopSelf 方法,来在任务完成的时候结束掉自己。 
但是这个时候就会出现一个问题,如果startService调用了2次,那么就执行了两次onStart操作,在第一次onStart操作结束以后,Service可能会认为任务已经完成,并结束掉自己,这个时候第二次的onStart可能还没结束,导致了任务还未完成就被强行关闭了。 
而startid代表当前onStart被调用的一个编号,在结束Service时候,调用stopSelf(startid),这样Service就可以检查,此startid是否是最近一次调用的,如果是,那么才结束Service,否则不结束。 

11、特殊的Service--   IntentService

(1). 异步服务IntentService

默认Service是运行在主线程内的 ,如果在Service内运行一个耗时操作就会阻塞主线程,可能导致ANR,为此我们可以在Service中自己新建线程去执行耗时操作,不过Android系统引入了IntentService方便的解决了这个问题, IntentService会启动一个工作线程去完成用户onHandleIntent中定义的操作,需要注意的是对于同一个IntentService的多次请求(startService调用),

IntentService使用队列的方式将请求的Intent加入队列,然后开启一个worker thread(线程)来处理队列中的Intent,对于异步的startService请求,IntentService会处理完成一个之后再处理第二个,每一个请求都会在一个单独的worker thread中处理,不会阻塞应用程序的主线程,这里就给我们提供了一个思路,如果有耗时的操作与其在Service里面开启新线程还不如使用IntentService来处理耗时操作。

在同一个线程中处理,一次只会执行一个请求的onHandleIntent函数。对于不同IntentService的同时请求,在不同的线程中处理,所以每个请求的onHandleIntent函数可以并发执行。示例代码如下:

IntentService示例
复制代码
public class MyIntentService extends IntentService {    public MyIntentService(){        super("MyIntentService");    }    @Override    protected void onHandleIntent(Intent intent) {        try {            System.out.println("IntentService1 Begin Sleep. " + "Thread name: " + Thread.currentThread().getName()                               + ", Thread Id: " + Thread.currentThread().getId());            Thread.sleep(3000);            System.out.println("IntentService1 End. ");        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
复制代码

在AndroidManifest.xml文件中注册服务<service android:name=".MyIntentService"/>,在Activity中定义service对象private Intent myIntentServiceIntent = new Intent(ServiceDemo.this, MyIntentService.class);在onCreate函数中startService(myIntentServiceIntent)启动服务;

从上面我们可以看出
a. IntentService只需要重定义onHandleIntent函数并定义一个无参构造函数(xml中服务注册初始化时使用)即可。
b. IntentService服务在onHandleIntent执行结束后会自动关闭。

 

IntentService和普通Service的区别如下
a. 普通Service运行在主线程中,IntentService运行在一个工作线程中不会阻塞主线程。
b. 普通Service需要手动调用停止接口,IntentService自动停止。
c. IntentService的onStartCommand函数根据mRedelivery属性值返回START_REDELIVER_INTENT或START_NOT_STICKY,而普通Service自定义返回。

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的生命周期跟你的处理的任务是一致的.所以这个类用下载任务中非常好,下载任务结束后服务自身就会结束退出.


 


参考:
http://developer.android.com/reference/android/app/Service.html

http://developer.android.com/guide/components/services.html

http://developer.android.com/reference/android/app/IntentService.html

0 0
原创粉丝点击