Binder is like RPC in java. It enables multi-processes communication. Now we will talking about how to bind service using IBinder class.java
總共有3種bind service方法:ide
1.使用IBinder classthis
2.使用Messanger classspa
3.使用AIDLorm
這裏只討論IBinder class方法。blog
用IBinder class 來bind service分如下幾步:繼承
Service建立步驟:接口
1.建立一個新的工程名字爲「BindServiceUsingBinderClass」;get
2.在建立的Application中建立一個Service.java繼承Service;it
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; } }; }