Android Programming Tutorials

(Romina) #1
High-Priced Help

Step #2: Create the Alarm BroadcastReceiver.................................


Next, we need to create a Java object from a public class with a public


method that we can inject into the Javascript environment of our WebView


that will give us access to the user's idenit.ca screen name.


To that end, add the following inner class to HelpPage:


public class CustomHelp {
SharedPreferences prefs=null;

CustomHelp() {
prefs=PreferenceManager
.getDefaultSharedPreferences(HelpPage.this);
}

public String getUserName() {
return(prefs.getString("user", "<no account>"));
}
}

Step #3: Doing the Work....................................................................


Just because we created the CustomHelp inner class does not mean Javascript


has access to it. Instead, we need to give the WebView an instance of


CustomHelp and associate it with a name that will be used to make the


CustomHelp instance look like a global variable in Javascript.


Add the following lines to onCreate() in HelpPage:


browser.addJavascriptInterface(new CustomHelp(),
"customHelp");

The entirety of onCreate() in HelpPage should now look like this:


@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.help);

browser=(WebView)findViewById(R.id.webkit);
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new CustomHelp(),

258
Free download pdf