您的位置:首页 > 移动开发 > Android开发

Android中的Service全面总结(修正过)

2013-11-11 11:05 357 查看
文章出处:http://www.cnblogs.com/newcj/archive/2011/05/30/2061370.html

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启动的服务主要用于启动一个服务执行后台任务,不进行通信。停止服务使用stopService
bindService启动的服务该方法启动的服务要进行通信。停止服务使用unbindService
startService同时也bindService启动的服务停止服务应同时使用stopService与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中的代码框架:
package com.newcj.test;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class LocalService1 extends 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 的代码:
// 启动一个 Activity
startActivity(new Intent(this, LocalService1.class));
...
// 停止一个 Activity
stopService(new Intent(this, LocalService1.class));


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

5、Local与Remote服务绑定

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

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

Service中的代码:
package com.newcj.test;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class LocalService extends Service { 
    /**
     * 在 Local Service 中我们直接继承 Binder 而不是 IBinder,因为 Binder 实现了 IBinder 接口,这样我们可以少做很多工作。
     * @author newcj
     */
    public class SimpleBinder extends 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中的代码:
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 Main extends 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、创建前台服务

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

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

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 ForegroundService extends 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

本文代码下载地址:http://files.cnblogs.com/newcj/ServiceTest.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: