문제

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.

도움이 되었습니까?

해결책

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" ...>

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top