Xamarin Android Services

Hi i'm trying to make a Android "Started" Service with Xamarin or MonoDroid. But Currently i'm hung up on some code.

In the sample for binding a Activity to a Service running in a remote process, they have a nested IServiceConnection implementation called "DemoServiceConnection".

Now in Java it seems that the nested ServiceConnection has the ability to access the parent class fields directly, which is something i've never seen before in C#.

Sample Java Code:

public class ActivityMessenger extends Activity {
    Messenger mService = null;
    boolean mBound;

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }
        ...
}

However In Xamarin/MonoDroid I'm supposed to make a nested Class with a Constructor that takes a reference to the current Activity.

Xamarin C# Code:

public class DemoMessengerActivity : Activity
{
    bool isBound = false;
    Messenger demoMessenger;
    ...

    class DemoServiceConnection : Java.Lang.Object, IServiceConnection
    {
        DemoMessengerActivity activity;

        public DemoServiceConnection (DemoMessengerActivity activity)
        {
            this.activity = activity;
        }
        public void OnServiceConnected (ComponentName name, IBinder service)
        {
            activity.demoMessenger = new Messenger (service);
            activity.isBound = true;
        }
        ...
    }
}

But this doesn't change any of the fields in the parent class. which is needed to work with the data in the Activity itself as is show in the Sample.

Ex.

public class DemoMessengerActivity : Activity
{
    ...
    protected override void OnCreate(Bundle bundle)
    {
        ...
        button.Click += delegate {
            if (isBound) {

                Message message = Message.Obtain ();
                Bundle b = new Bundle ();
                b.PutString ("InputText", "text from client");
                message.Data = b;

                demoMessenger.Send (message);
            }
    }
}

If anyone could explain how this works or some other trick I could use to accomplish this would be very helpful.

Thanks'

Sign In or Register to comment.