Search code examples
androidandroid-activityassetsandroid-context

Context and Activity's reference


I've some problem with the design of my app, especially opening assets from a class, different from the main Activity.

This part of my project is a webserver and there are 2 classes: WebServer and WebPage. WebServer has these methods: start(), get(), post(), send(WebPage) and some constructors;

WebPage has 2 variables: String head (the HTTP header) and byte [] body (the content who can be text or any file). WebPage has one method, byte[] getFile(String filename), used by constructors to save the bytes of the file in body. The file is an asset.

When the Activity starts (onCreate()), it creates an instance of WebServer, call start() and stay in listening. When the server receives a GET request, it parses it and it creates a WebPage object using the filename to open the asset. Finally WebServer just sends the page with send(WebPage).

Which is the best way to obtain an Activity's reference from the WebPage class?


Solution

  • Since your question should be more explained: you want to keep your WebServer as generic as possible so that it works on Android and on a PC.

    Do the following. Create your generic WebServer:

    public class WebServer{
        int port;
        public WebServer(int port){
            this.port = port;
        }
        ////////bla bla bla
    }
    

    Create your android WebServer

    public class AndroidWebServer extends WebServer{
        Context mContext;
        public webserver(Context mContext, int port){
            super(port);
            this.mContext = mContext;
        }
    }
    

    Old Answer

    Use the very usual way and don't worry about memory leak.

    public class webserver{
        Context mContext;
        public webserver(Context mContext){
            this.mContext = mContext;
        }
    }
    

    In your activity:

    webserver A = new webserver(this);