通过Ibinder类Bind service
Binder is like RPC in java. It enables multi-processes communication. Now we will talking about how to bind service using IBinder class.
总共有3种bind service方法:
1.使用IBinder class
2.使用Messanger class
3.使用AIDL
这里只讨论IBinder class方法。
用IBinder class 来bind service分以下几步:
Service创建步骤:
1.创建一个新的工程名字为“BindServiceUsingBinderClass”;
2.在创建的Application中创建一个Service.java继承Service;
3.在Service.java中创建一个LocalBinder内部类继承Binder;
4.实现service中onBind()方法并返回“LocalBinder的实例。
Activity创建步骤:
1.创建Client Activity,并创建一个”ServiceConnection"接口的instance。
2.实现该接口的两个方法-onServiceConnected()和onServiceDisconnected().
3.在onServiceConnected()方法中,把iBinder instance cast成localBinder类。
4.实现onStart() 方法并用bindService()绑定服务。
5.实现onStop() 方法,并用unbindService()解除绑定。
Service.java代码如下:
//Service.java public class Service extends Service{ IBinder mBinder = new LocalBinder(); @Override public IBinder onBind(Intent intent) { return mBinder; } public class LocalBinder extends Binder { public Server getServerInstance() { return Server.this; } } public String getTime() { SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return mDateFormat.format(new Date()); } }
Client.java
//Client.java public class Client extends Activity { boolean mBounded; Server mServer; TextView text; Button button; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView)findViewById(R.id.text); button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { text.setText(mServer.getTime()); } }); } @Override protected void onStart() { super.onStart(); Intent mIntent = new Intent(this, Server.class); bindService(mIntent, mConnection, BIND_AUTO_CREATE); }; ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { Toast.makeText(Client.this, "Service is disconnected", 1000).show(); mBounded = false; mServer = null; } public void onServiceConnected(ComponentName name, IBinder service) { Toast.makeText(Client.this, "Service is connected", 1000).show(); mBounded = true; LocalBinder mLocalBinder = (LocalBinder)service; mServer = mLocalBinder.getServerInstance(); } }; @Override protected void onStop() { super.onStop(); if(mBounded) { unbindService(mConnection); mBounded = false; } }; }