Create a Service with a UI

I'm trying to create an overlay after I press a start button (when I say overlay I mean like the Facebook messenger overlay that stays on top of everything). So far I was able to do this using the code below. This works just fine, but I don't like creating my "view" programmatically, I would rather lay it out in XAML somewhere. How do I go about doing this and then loading it? This may be a stupid/simple question, but I'm just starting out with Android / Xamarin so forgive my ignorance.

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    public void HandleStartClick()
    {
        var serviceIntent = new Intent(this, typeof(OverlayService));
        this.StartService(serviceIntent);
    }
}

[Service(Label = "OverlayService", Icon = "@mipmap/icon")]
public class OverlayService : Service
{
    public override void OnCreate()
    {
        base.OnCreate();
        var windowManager = this.GetSystemService(WindowService).JavaCast<IWindowManager>();
        var button = new Button(this) { Text = "Test" };
        var layoutParams = new WindowManagerLayoutParams(
                                        ViewGroup.LayoutParams.WrapContent,
                                        ViewGroup.LayoutParams.WrapContent,
                                        WindowManagerTypes.ApplicationOverlay,
                                        WindowManagerFlags.NotFocusable,
                                        Format.Translucent)
                                    {
                                        Gravity = GravityFlags.Top | GravityFlags.Left,
                                        X = 0,
                                        Y = 50
                                    };
        windowManager.AddView(button, layoutParams);
    }
}

Answers

  • jezhjezh Member, Xamarin Team Xamurai

    You could try to create a layout file(eg: test.axml )
    Then Inflate this layout.

       var layout = LayoutInflater.From(this).Inflate(Resource.Layout.test, null);
    
Sign In or Register to comment.