Chrisの梳羽之礁

A look of quick intelligence and soft refinement
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Service基础知识

Posted on 2011-02-17 16:11  Chrisfang6  阅读(456)  评论(1编辑  收藏  举报


一、创建/启动/销毁Service

方法:全部通过Intent来执行。

Intent myIntent = new Intent(MyActivity.this, MyService.this);

……

// create/start Service
MyActivity.this.startService(myIntent);

……

// destroy Service
MyActivity.this.stopService(myIntent);

二、将Service与Activity绑定

目的:用Activity控制Service,及获取其状态
方法:通过ServiceConnection来绑定/解绑定Service,通过Binder获取Service实例

// create a ServiceConnection
private ServiceConnection serviceConnection = new ServiceConnection() {
 @Override
 public void onServiceConnected(ComponentName name, IBinder service)
 {
  // get Service implement from here.
  myService = ((MyService.MyBinder) service).getService();
 }

 @Override
 public void onServiceDisconnected(ComponentName name)
 {
  myService = null;
 }
};

……

// bind Service
MyActivity.this.bindService(myIntent, myServiceConn, Context.BIND_AUTO_CREATE);

……

// unbind Service
MyActivity.this.unbindService(myServiceConn);

而在MyService中,

// create Binder
public class MyBinder extends Binder
 {
  // You can create methods like below as you need.
  MyService getService()
  {
   return MyService.this;
  }
 }

……

@Override
public IBinder onBind(Intent intent)
{
 return myBinder;
}

三、获取系统服务

目的:通过系统服务对窗口、来电、剪切板等进行操作。

// get system Service
Object myActivity.getSystemService(String name);
// name is defined in Context
// Cast the object to what you need