一、创建/启动/销毁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