public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final Random mGenerator = new Random();
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
}
public class BindingActivity extends Activity {
MyService mService;
boolean mBound = false;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
public void onButtonClick(View v) {
if (mBound) {
int num = mService.getRandomNumber();
Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
This implementation is full of boilerplate code. In Scala, we can rewrite it as follows:
class MyService extends LocalService {
private val generator = new Random()
def getRandomNumber() = generator.nextInt(100)
}
class Activity extends SActivity {
val random = new LocalServiceConnection[MyService]
def onButtonClick(v:View) {
if(random.connected) {
toast("number: " + random.service.getRandomNumber())
}
}
}
This code snippet does the same thing with the original Java code. All of the clutters are encapsulated in LocalService and LocalServiceConnection, so you can just focus on your idea.The full source code of these traits can be found here
No comments:
Post a Comment