Android开发经验谈首页投稿(暂停使用,暂停投稿)Android

# Service 基础及注意点

2016-05-21  本文已影响195人  伍零一

引言


文档内容主要翻译自google文档,也有个人补充。

Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.

Service是一个可以在后台执行长时间运行且不提供用户交互操作的应用组件.其他应用组件(activity,fragment)可以在后台运行一个service即使用户跳转到其他应用。除此之外,一个组件可以和service绑定进行交互,例如IPC机制(AIDL)。举个例子,service可以在后台处理网络传输,播放音乐,执行文件I/O,或者和content provider交互。

使用形式

Service有两种形式:

函数介绍


如果你想要创建一个service,你必须创建Service的子类,实现并覆盖某些方法。

我们应该覆盖的方法有:

生命周期


service_lifecycle.png

生命周期根据两种service的两种形式分为两种:

启动后的service在不用的时候调用stopService来停止它,系统会自动销毁.

绑定后的service在不用的时候调用unbindService来停止它,系统会自动销毁.

列举Service通信的情况


Activity和Service通信

Activity和Service进行通信会通过绑定的形式,在onBind method中返回Binder实例,然后Binder中实现当前Service的引用,这样Activity和Service 就建立起通信。

/** 
 * 返回一个Binder对象 
 */  
@Override  
public IBinder onBind(Intent intent) {  
    return new MsgBinder();  
}  
  
public class MsgBinder extends Binder{  
    /** 
     * 获取当前Service的实例 
     * @return 
     */  
    public MsgService getService(){  
        return MsgService.this;  
    }  
}  

AIDL

AIDL里面通过service来当做server端。

总结


上一篇下一篇

猜你喜欢

热点阅读