Question

I have a network class making use of the following lib: Lib Docs with 4 function to make a get, post delete and put request to the server. here is the simplified version:

 public static void get(Context context, String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {          
    httpClient.get(context, getAbsoluteUrl(url), params, responseHandler);
} 

Now instead of having to pass the context through via a paramter, Is there no possible way to some how get the context of the calling activity inside the fucntion?

some thing along the lines of:

public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
    Context context = getCallignActivtyCntext() // <====== some thing like this
    httpClient.get(context, getAbsoluteUrl(url), params, responseHandler);
}

the reason I need the specific context is because I have to cancel all network requests when an activity is destroyed, and it groups or identifies all requests by the context.

Was it helpful?

Solution

If you don't actually need the specific context of the caller for your methods, you can just use the Application context through getApplicationContext()

To statically access your Application context you can do something like this:

public class CustomApplication extends Application{

    private static Context context;

    public void onCreate(){
        super.onCreate();
        this.context = getApplicationContext();
    }

    public static Context getContext() {
        return instance;
    }
}

Then in your manifest you declare your application name to match your custom class

<application android:name="com.path.to.class.CustomApplication" ...>

OTHER TIPS

I don't believe so, no context would exist within a static method. The only way would be to pass a parameter in. You could get this from an intent, but not a standard static method call. There might be a solution but I highly doubt it.

While this is possible by inspecting the stack trace, this would certainly be more complicating than just passing the context.

There is no simpler solution. Moreover, getting the caller of a method is not recommended for security reasons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top