Update the Android Main UI from a WebView — PhoneGap Plugin
A simple PhoneGap plugin that lets JavaScript in a WebView update the native Android UI, such as the action bar.
We recently developed a hybrid Android application that uses a native action bar alongside a PhoneGap WebView. On several occasions, the WebView needed to communicate with the main UI thread. You can do this by creating a PhoneGap plugin, and the code below is a simple example.
I named the file Helper.java, in the package com.plugins.ui.
package com.plugins.ui;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.sarathdr.app.MyApp;
import com.sarathdr.ui.MainActivity;
import com.sarathdr.ui.TeamSelectionActivity;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
/**
* Created by Sarath DR on 15/04/2014.
*/
public class Helpers extends CordovaPlugin
{
CallbackContext callbackContext;
private Context context;
private Integer tabIndex;
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
this.context = cordova.getActivity().getApplicationContext();
this.callbackContext = callbackContext;
if (action.equals("moveTab")) {
tabIndex = args.getInt(0);
this.moveTab();
return true;
}else if(action.equals("showToast")){
String message = args.getString(0);
this.showToast( message );
}
return false;
}
public void moveTab()
{
// Calls a function in the main activity to move the action bar tab
cordova.getActivity().runOnUiThread(new Runnable(){
public void run() {
MainActivity.moveTab(tabIndex);
callbackContext.success();
} });
}
// Show toast message
public void showToast(String message) {
if (message != null && message.length() > 0) {
Toast.makeText(cordova.getActivity().getApplicationContext(),
message, Toast.LENGTH_LONG).show();
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}