Skip to content

Instantly share code, notes, and snippets.

Created December 31, 2016 19:41
Show Gist options
  • Save anonymous/13d7cbe3d318d4c7d64a24e139026be5 to your computer and use it in GitHub Desktop.
Save anonymous/13d7cbe3d318d4c7d64a24e139026be5 to your computer and use it in GitHub Desktop.
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
WebView webView;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
setContentView(R.layout.activity_main);
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Make it possible to debug on your PC using "chrome://inspect/#devices"
WebView.setWebContentsDebuggingEnabled(true);
}
webView = new WebView(getApplicationContext());
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
webView.setVisibility(View.GONE);
}
@Override
public void onPageFinished(final WebView view, String url) {
Log.e("checking", "MYmsg");
webView.loadUrl("javascript:(function() { " +
"document.body.innerHTML = '<p>test<p>';" + "})()");
webView.loadUrl("javascript: window.CallToAnAndroidFunction.setVisible()");
}
});
webView.setVisibility(View.INVISIBLE);
webView.addJavascriptInterface(new myJavaScriptInterface(), "CallToAnAndroidFunction");
webView.loadUrl("https://example.com");
// if you need to debug visually. Then uncomment the next line.
//setContentView(webView);
}
@Override
protected void onDestroy() {
// Destroy the webview, otherwise it's kept in memory.
webView.destroy();
super.onDestroy();
}
public class myJavaScriptInterface {
@JavascriptInterface
public void setVisible() {
Runnable runnable = new Runnable() {
@Override
public void run() {
// The nested `MainActivity.this.runOnUiThread` isn't needed.
webView.setVisibility(View.VISIBLE);
Log.e("Testing", "no");
Toast.makeText(MainActivity.this, "Reached JS", Toast.LENGTH_LONG).show();
}
};
// Show the toast and log 2 seconds from now.
// If you want it to run as soon as possible.
// Then replace the handler.postDelayed with `MainActivity.this.runOnUiThread(runnable)` or set the delay to 0.
handler.postDelayed(runnable, 2000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment