android学习笔记之十服务(Service)

来源:互联网 发布:android rtmp推流源码 编辑:程序博客网 时间:2024/05/18 02:50

Service拥有一个单独进程的模块.

1,继承自Service类,须实现public IBinder onBind(Intent intent)


2,通过startServie触发运行,stopService终止运行
   生命周期: onCreate(如果是第一次运行) -> onStart -> onDestroy


3,绑定触发(调用4功能前提)
   boolean bindService (Intent service, ServiceConnection conn, int flags) //flags:Context.BIND_AUTO_CREATE
   ServiceConnection须实现两个方法
     onServiceConnected(ComponentName name, IBinder service)
     onServiceDisconnected(ComponentName name)
   相对应的方法unbindService (ServiceConnection conn)
   生命周期: onCreate(如果是第一次运行)-> onBind(仅一次,不可多次绑定)--> onUnbind-> onDestory

4,怎样提供客户端调用Service方法
   a,新建aidl文件定义XX接口
   b,实现XX接口的XX.Stub()该类下实现XX接口定义的方法
   c,XX.Stub()实例返回给public IBinder onBind(Intent intent)
   d,在ServiceConnection.onServiceConnected(ComponentName name, IBinder service) 中通过
     XX.Stub.asInterface(service)返回XX接口实例


5,获取系统正在运行的Services
   ActivityManager am = (ActivityManager)Activity.getSystemService(ACTIVITY_SERVICE);
   am.getRunningServices();

原创粉丝点击