Passing context from Android Native App to Web View Activity, while building a Hybrid App


​This post could also have been titled setting cookie in Javascript from android native to Webview .

While building a hybrid app, 1 problem that we faced is passing context from the App to the webview. We had spring security in place. So any unauthenticated calls to the web services always redirected us to the login page.

We had a mechanism where the user logs in the native app and then we needed to pass the context to the webview which would be displaying the HTML 5 cross platform app. If we did not share the context , the user would be redirected to the login page and all user data would have been lost .
Now while building the native android app, we have used DefaultHttpClient to save the cookies in the cookie store .
httpClient.setCookieStore(mCookie);
Now we needed to pass this session information from the httpClient to the webview. Here’s how to do it.
Get all the cookies from the cookie store of the httpclient

List cookies = httpClient.getCookieStore().getCookies();

for (int i = 0; i < cookies.size(); i++)

{ cookie = cookies.get(i); }

Cookie sessionCookie = cookie;

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.
To use the CookieSyncManager, the host application has to call the following when the application starts:

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(_webView.getContext());

In programming terms, Context is the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.
So here since we have the webview in the same activity as our code, we can replace ‘getcontext’ by ‘this’. As Both of them point to the current activity

Next, we create the cookiemanager .
CookieManager cookieManager = CookieManager.getInstance();

In Android there are 2 classes…android.webkit.CookieManagerjava.net.CookieManager

We will be using the one in android webkit. Webkit cookie manager manages the cookies used by an application’s WebView instances. The java.net.Cookiemanager is used for httpConnections and not for webview.

cookieManager.setAcceptCookie(true);

cookieManager.removeSessionCookie();

setAcceptCookie(boolean accept)
Sets whether the application’s WebView instances should send and accept cookies.removeSessionCookie()
Removes all session cookies, which are cookies without an expiration date.
First one is needed as otherwise we cannot set cookies in our webview. Second one is important because it removes junk data in our web view, which we might not have removed.

SystemClock.sleep(1000); String cookieString = sessionCookie.getName() + “=” + sessionCookie.getValue() + “; domain=” + sessionCookie.getDomain(); cookieManager.setCookie(“http://10.0.2.2&#8243;, cookieString+”; username=”+message); CookieSyncManager.getInstance().sync();

The system.sleep is important as the remove session cookie takes place asynchronously hence, we need to wait for it to get over. This is a small hack which is very important.
The next steps are pretty forthright. We set the cookie in the cookiemanager, pass the data from the app to the webview using query string

Note that even sync() happens asynchronously, so don’t do it just as your activity is shutting down.

The rest of the code is shown for completion

_webView.getSettings().setJavaScriptEnabled(true);
_webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(“Loading…”);
activity.setProgress(progress * 100);

if(progress == 100)
activity.setTitle(R.string.app_name);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return shouldOverrideUrlLoading(view, url);

}
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(“MyApplication”, cm.message() + ” — From line ”
+ cm.lineNumber() + ” of ”
+ cm.sourceId() );
return true;
}
});

_webView.loadUrl(“http://yourdomain.com?data=”+message);

}

 

We have used the chrome webclient so as to see and debug the javascript code.Overriding url is necessary as we want the webview to handle all clicks on the hyperlinks.

I have tested this in android 2.3,and this is a nice way to pass cookies between the http client and the webview.

Advertisements

One response to “Passing context from Android Native App to Web View Activity, while building a Hybrid App

  1. Hi there! I know this is kinda off topic however I’d
    figured I’d ask. Would you be interested in trading
    links or maybe guest authoring a blog article or vice-versa?
    My blog goes over a lot of the same subjects as yours and
    I feel we could greatly benefit from each other.

    If you happen to be interested feel free to shoot me an e-mail.

    I look forward to hearing from you! Fantastic blog by the way!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s