Activity通过bindService启动Service后Activity和Service之间的通信!

来源:互联网 发布:淘宝不能重新激活店铺 编辑:程序博客网 时间:2024/04/27 16:48

最近在看同一个程序中Service的两种驱动方式时,起以Bind启动然后可以进行ServiceActivity之间的相互通信。一直没看明白,在翻看SDK时发现一个例子,特别摘抄如下:

这个时BindingService继承自Activity,然后通过点击按钮来启动Service

public class BindingService extends Activity {   private static final String TAG = "BindingService";    // mService负责接收Service传过来的对象LocalService mService;boolean mBound = false;Button bindBtn;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                bindBtn = (Button) findViewById(R.id.bindBtn);        bindBtn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubLog.i(TAG, "OnClick....");if(mBound) {int num = mService.getRandomNumber();Toast.makeText(BindingService.this, num+"", Toast.LENGTH_LONG).show();}}                 });    }@Overrideprotected void onStart() {super.onStart();// Bind to LocalServiceIntent intent = new Intent(this, LocalService.class);Log.i(TAG, "onStart.....onBind");bindService(intent, mConnection, Service.BIND_AUTO_CREATE);}@Overrideprotected void onStop() {super.onStop();// UnBind from the serviceif(mBound) {unbindService(mConnection);mBound = false;}}// Defines callbacks for service binding, passed to bindService()private ServiceConnection mConnection = new ServiceConnection() {@Override      // 在Service断开的时候调用这个函数public void onServiceDisconnected(ComponentName name) {// 另外说明在这里打log或者是使用Toast都不能显示,不知道是怎么回事mBound = false;}@Override// 在Service连接以后调用这个函数public void onServiceConnected(ComponentName name, IBinder service) {// we have bound to LocalService, cast the IBinder and get LocalService instance// 获得Service中的Binder对象// 另外说明在这里打log或者是使用Toast都不能显示,不知道是怎么回事LocalBinder binder = (LocalBinder) service;// 通过Binder对象获得Service对象,然后初始化mServicemService = binder.getService();Log.i(TAG, "onServiceConnected.....");System.out.println("onServiceConnected.....");mBound = true;}};}public class LocalService extends Service {// Binder given to clients// 返回一个Binder对象private final IBinder mBinder = new LocalBinder();// Random number generatorprivate final Random mGenerator = new Random();/*** * Class used for the client Binder.Because we know this service always * runs in the same process as its clients */public class LocalBinder extends Binder {LocalService getService() {// return this instance of LocalService so clients can call public methodreturn LocalService.this;}}@Override// 如果是通过startService()函数启动的时候,这个函数是不起作用的。// public void onServiceConnected(ComponentName name, IBinder service) 返回的Activity// IBinder service 对象public IBinder onBind(Intent intent) {// IBinder通信关键是利用Activity中的IBider对象获得service对象,然后调用service中的函数// 传给Activity一个Binder对象,通过这个Binder对象调用getService()获得Service对象return mBinder;}// method for clientspublic int getRandomNumber() {return mGenerator.nextInt(100);}}


 

原创粉丝点击