leonardo
leonardo

Reputation: 75

MonoDroid simple web server

I've created a simple web server that runs on the Android device that basically response with Hello World that used to work prior to Preview 11. Was there any major change that causes this to no longer work or am I doing something wrong? The application crashes on context.Response.OutputStream.Write( buffer, 0, buffer.Length );

Code:

public class Activity1 : Activity
{
    private HttpListener listener;

    protected override void OnCreate( Bundle bundle )
    {
        base.OnCreate( bundle );

        // Set our view from the "main" layout resource
        SetContentView( Resource.Layout.Main );

        // Get our button from the layout resource,
        // and attach an event to it
        var button = FindViewById<Button>( Resource.Id.MyButton );

        button.Click += button_Click;
    }

    private void button_Click( object sender, EventArgs e )
    {
        try
        {
            if ( !HttpListener.IsSupported )
                return;

            listener = new HttpListener();
            listener.Prefixes.Add( "http://+:8001/" );
            listener.Start();
            listener.BeginGetContext( HandleRequest, listener );
        }
        catch ( Exception )
        {
            throw;
        }
    }

    private void HandleRequest( IAsyncResult result )
    {
        HttpListenerContext context = listener.EndGetContext( result );

        string response = "<html>Hello World</html>";
        byte [] buffer = Encoding.UTF8.GetBytes( response );

        context.Response.ContentLength64 = buffer.Length;
        context.Response.OutputStream.Write( buffer, 0, buffer.Length );
        context.Response.OutputStream.Close();

        listener.BeginGetContext( HandleRequest, listener );
    }
}

log:

I/ActivityManager( 112): Process torqsoftware.testwebserver (pid 3044) has died.

I/WindowManager( 112): WIN DEATH: Window{44d15120 torqsoftware.testwebserver/monodroidwebservertest.Activity1 paused=false}

D/Zygote ( 58): Process 3044 terminated by signal (4)

V/RenderScript_jni( 199): surfaceCreated

V/RenderScript_jni( 199): surfaceChanged

I/UsageStats( 112): Unexpected resume of com.android.launcher while already resumed in torqsoftware.testwebserver

W/InputManagerService( 112): Got RemoteException sending setActive(false) notification to pid 3044 uid 10062

Thanks Leo

Upvotes: 1

Views: 1799

Answers (1)

Ankur
Ankur

Reputation: 33657

It seems to be related to the fact that an Activity is "paused" when user moves on to another application in android. As in this case you may have opened browser to access the http server which is running in the paused activity. I would suggest you to implement the http server as a Service and not as an activity.

Upvotes: 3

Related Questions