service

service 是一个可以长期运行在后台的application 组件。service 不提供user interface。当一个application 组件启动service后,service就开始运行。即使用户switch到其他application。application 组件也可以绑定一个service,然后和这个service 交互,甚至可以进行进程间通讯(IPC)。service 可以后台控制网络传输,播放音乐,读取io 文件,以及与content provide进行交互。
一个service 本质上有两种形式:需要注意的是service 可以同时处于started + Bound状态.
started:当application 组件call startService()后,service就处于started.这时候service 就可以在后台独立运行,即使启动它的application 组件被 销毁,当这个service 要做的事情完成是,如下载成功一个文件后。必须调用stopService()或者stopService()来停止service.

Bound:当application 组件call bindService()后,service就处于Bound.处于这种状态的service 和组件之前通过client-server的方式交互。application 组件 可以发送request给service,可以获取结果,可以IPC。只要有application bound 到service,service 就会一直运行,可以有多于一个的application 组 件连接到service。当所有application 组件unbound service后,service 就会销毁.
service 默认是运行在main thread,所以在service中cpu 密集型工作会block main thread的操作,你应该为service 单独创建一个thread运行cpu 密集型job.但这样application 和 运行在单独thread 中的service 交互的时候,可能由于service 在运行cpu 密集型job,而造成ANR.


要创建一个service,你必须定义一个class extend service。在这个new class中必须要实现下面四个callback。
onStartCommand:startService()->onCreate()->onStartCommand()->onDestroy()
onBind:bindService()->onCreate()->onBind()->onUnbind()->onDestroy()
onCreate:
onDestroy:
你必须在manifest文件中<service>中声明service,就像下面这样。
<manifest ... >
  ...
  <application ... >
      <service android:name=".ExampleService" />
      Android:exported=false// 这个service 只能在本application中运行。增强secure。
  </application>
</manifest>

要创建一个service,你必须定义一个class extend IntentService。这个子类你只要实现onHandleIntent就行.

service的子类每次处理一个request,如果你不需要service同时处理多条quest,那你最好实现IntentService的子类,你只要实现onHandleIntent方法就行了
一般我们让IntentService run在单独的线程中,service 会出来才理你个OnstartCommand 中发送过来的Intent,当所有的request 出来完时,IntentService 会自动call stopSelf().
如果你要重写IntentService的callback method,例如:onCreate(),OnStartCommand(),或者oNDestroy(),一定要call super implement。否则的话IntentService 没办法控制worker thread的生命周期.
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
    return super.onStartCommand(intent,flags,startId);
}
不用call super.onBind()和super.onHandleIntent()
如果要同时出来多条quest 最好实现service的子类+HandlerThread的方式进行.
当调用onStartCommand()的时候会返回一个整数。这个值描述当service被系统kill后如何进行。这个返回值只能是下面三个:
START_NOT_STICKY :在执行onStartCommand()后,系统kill service,在没有pending intent的情况下不好recreate service.
START_STICKY :系统kill service后,重新call onStartCommand(),但是不要重新发送最后一个intert,而是发送一个空 intent 给onStartCommand(),如果要发送pending intent 给service.
START_REDELIVER_INTENT:重新启动service,发送最后一个intent 和 pending intent.
可以call startForeground 来让service 运行在前台,这样即使系统memory比较紧张的时候,也不会kill掉前台service.与之对应的是通过stopForeground来移除前台service.

我们来看看IntentService的源码
53可知IntentService 继承service,也是一个抽象类,不能实例化。
59 定义可一个handle的子类,在其handleMessage中调用onHandleIntent,这也是IntentService子类唯一要实现的方法.
108 new 一个handlerThread,并start,可知IntentService 用于一个独立的thread.
53 public abstract class IntentService extends Service {
54    private volatile Looper mServiceLooper;
55    private volatile ServiceHandler mServiceHandler;
56    private String mName;
57    private boolean mRedelivery;
58
59    private final class ServiceHandler extends Handler {
60        public ServiceHandler(Looper looper) {
61            super(looper);
62        }
63
64        @Override
65        public void handleMessage(Message msg) {
66            onHandleIntent((Intent)msg.obj);
67            stopSelf(msg.arg1);
68        }
69    }
70
71    /**
72     * Creates an IntentService.  Invoked by your subclass's constructor.
73     *
74     * @param name Used to name the worker thread, important only for debugging.
75     */
76    public IntentService(String name) {
77        super();
78        mName = name;
79    }
80
81    /**
82     * Sets intent redelivery preferences.  Usually called from the constructor
83     * with your preferred semantics.
84     *
85     * <p>If enabled is true,
86     * {@link #onStartCommand(Intent, int, int)} will return
87     * {@link Service#START_REDELIVER_INTENT}, so if this process dies before
88     * {@link #onHandleIntent(Intent)} returns, the process will be restarted
89     * and the intent redelivered.  If multiple Intents have been sent, only
90     * the most recent one is guaranteed to be redelivered.
91     *
92     * <p>If enabled is false (the default),
93     * {@link #onStartCommand(Intent, int, int)} will return
94     * {@link Service#START_NOT_STICKY}, and if the process dies, the Intent
95     * dies along with it.
96     */
97    public void setIntentRedelivery(boolean enabled) {
98        mRedelivery = enabled;
99    }
100
101    @Override
102    public void onCreate() {
103        // TODO: It would be nice to have an option to hold a partial wakelock
104        // during processing, and to have a static startService(Context, Intent)
105        // method that would launch the service & hand off a wakelock.
106
107        super.onCreate();
108        HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
109        thread.start();
110
111        mServiceLooper = thread.getLooper();
112        mServiceHandler = new ServiceHandler(mServiceLooper);
113    }
114
115    @Override
116    public void onStart(Intent intent, int startId) {
117        Message msg = mServiceHandler.obtainMessage();
118        msg.arg1 = startId;
119        msg.obj = intent;
120        mServiceHandler.sendMessage(msg);
121    }
122
123    /**
124     * You should not override this method for your IntentService. Instead,
125     * override {@link #onHandleIntent}, which the system calls when the IntentService
126     * receives a start request.
127     * @see android.app.Service#onStartCommand
128     */
129    @Override
130    public int onStartCommand(Intent intent, int flags, int startId) {
131        onStart(intent, startId);
132        return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
133    }
134
135    @Override
136    public void onDestroy() {
137        mServiceLooper.quit();
138    }
139
140    /**
141     * Unless you provide binding for your service, you don't need to implement this
142     * method, because the default implementation returns null.
143     * @see android.app.Service#onBind
144     */
145    @Override
146    public IBinder onBind(Intent intent) {
147        return null;
148    }
149
150    /**
151     * This method is invoked on the worker thread with a request to process.
152     * Only one Intent is processed at a time, but the processing happens on a
153     * worker thread that runs independently from other application logic.
154     * So, if this code takes a long time, it will hold up other requests to
155     * the same IntentService, but it will not hold up anything else.
156     * When all requests have been handled, the IntentService stops itself,
157     * so you should not call {@link #stopSelf}.
158     *
159     * @param intent The value passed to {@link
160     *               android.content.Context#startService(Intent)}.
161     */
162    @WorkerThread
163    protected abstract void onHandleIntent(Intent intent);
164}
165

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值