Android Bridge Popup

Michael Tran (mytee)
2 min readJul 23, 2018

Popup by Intent

Chapters: webview, JS2Java , Java2JS, Alert dialog, Popup Screen.

Lets call a popup screen from JavaScript thru the Java Bridge class.

In the previous chapters, we have already seen how it works. The logic is simple: add one more function in the bridge object, then call it from Javascript; then listen to the return message.

The idea is using intent activity. Ref https://developer.android.com/reference/android/app/Activity

The layout of popup screen can be either pure coded, or using res/layout with xml. We will try both. There will be two buttons on html, to call them in different format: with and without layout file.

We will add the code into the Bridge_protocol class.

// Show popup
@JavascriptInterface
public void showPopup(String Msg) {
Intent myIntent = new Intent(getApplicationContext(), Popup.class);
// startActivity(myIntent); //if no need return code
startActivityForResult(myIntent,100, null); // if required return value
}

The call startActivity(myIntent); is for the case you dont want to trap return value from the popup screen such as aboutbox, contact info or the like.

The way to trap the return is adding the function into the bridge class like this

// to get return from popup screen
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { System.out.println(“onActivityResult: “ + resultCode);
if (requestCode == 100) { // it is my code predefined as 100
if (resultCode == RESULT_OK) { System.out.println(“result ok onActivityResult: “ + resultCode);
} else {System.out.println(“result cancel onActivityResult: canceled”); } } }

There are two popup classes. You will find the one that uses layout xml file is very simple because most of the elements are dome via interface builder. The code to bind the class to the layout is to call setContentView() in popupScreen class.

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forecast); // using layout here
}

You can also close the screen by

this.finish(); // or onBackPressed();

By experiment, I found the onDestroy() called by both of them. Therefore, any can do.

The sample project is here https://github.com/myteeNatanwit/AndroidBridgePopup

--

--