I have created a class that extends Android's WebViewClient so I can make it a 'preview' only client - i.e. most navigation is not allowed.
When a user tries to navigate, I want to pop up a toast to remind them that they are in a limited preview view and that they can't navigate further.
BUT toast requires an activity Context.
In order to make the Context available I assign a context to a variable (appContext)in the class's constructor as follows:
public class nonInteractiveWebViewClient extends WebViewClient {
public boolean canBrowse = false;
public Context appContext;
public nonInteractiveWebViewClient(Context context) {
appContext = context;
}
@Override
public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
return true;
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String host = Uri.parse(view.getUrl()).getHost();
canBrowse = // logic here to determine whether to allow navigation
if (canBrowse) {
return false;
} else {
Toast.makeText(appContext, appContext.getString(R.string.link_test_preview_only), Toast.LENGTH_SHORT).show();
return true;
}
}
}
When I create the nonInteractiveWebViewClient object in the calling activity I call it with getApplicationContext() to pass the context to the constructor.
Is this a bad idea?
As @sajjad has noted before, shouldOverrideUrlLoading has access to a view and getContext() can be run on a view, so the appContext variable is redundant in this exmaple, however...
I am also intending to use this pattern in another class which houses a number of methods that are used by multiple activities and that needs access to the activity context in a number of it's methods. These methods are standalone functions that do not extend any existing methods that might have access to a context. Using the approach above in this other class will both simplify my code and cut down on the number of calls to getApplicationContext that the calling activities need to make, but I am concerned that it may cause a memory leak or something.
Is this a bad approach?
(When answering, please appreciate that I am an engineer and while I have some understanding of the underlying theories of programming I am by no means a CS. I like to write code to be as modular as possibel and to avoid duplication of code as much as possible, hence my tackling this issue this way.)