How To Create A WebView On Layout & Catch HTML code - Android Coding

One day, I needed to ensure the HTML code on mobile works, and checked every segment is ready in my WebView object. So, I found this way and share to everyone need it.

This is a simple code for tutorial in Java below:
 
 @SuppressLint({ "SetJavaScriptEnabled", "JavascriptInterface" })
 public class MainActivity extends Activity   
 {  
     private WebView mWebView;  
     private ProgressBar mProgress;  
     private boolean mPageLoading = false;  
     private static final String mUrl = [ The URL you want to go ];  
       
     @Override  
     protected void onCreate(Bundle savedInstanceState)   
     {  
         super.onCreate(savedInstanceState);  
         setContentView(R.layout.activity_main);  
           
         // Initialize WebView object.  
         mWebView = (WebView) findViewById(R.id.webview);  
         mProgress = (ProgressBar)findViewById(R.id.progressbar);  
         mProgress.setVisibility(View.GONE);  
         
         // Make the position of the loading progress bar be closer to the Action Bar
         int ItemHeight = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,   
             7, getResources().getDisplayMetrics() );  
         mProgress.setY(-ItemHeight);
           
         // Enable Javascript, cache, image, css, and so on.  
         WebSettings webSettings = mWebView.getSettings();  
         webSettings.setJavaScriptEnabled(true);  
         webSettings.setDefaultTextEncodingName("utf-8");  
         webSettings.setUseWideViewPort(true);  
         webSettings.setSupportZoom(true);  
         //webSettings.setRenderPriority(RenderPriority.HIGH);  
         webSettings.setBuiltInZoomControls(true);  
         webSettings.setJavaScriptCanOpenWindowsAutomatically(true);  
         webSettings.setSupportMultipleWindows(true);  
         webSettings.setAllowFileAccess(true);  
         webSettings.setDomStorageEnabled(true);  
       
         // set loading progress.  
         mWebView.setWebChromeClient(new MyWebChromeClient(this));  
       
         // Force links and redirects to open in the WebView instead of in a browser  
         mWebView.setWebViewClient(new MyAppWebViewClient(this));  
       
         // set javascript interaction.  
         // define "traceHTML" to be a javascript command(as a plug-in), and it will be called in
         // MyAppWebViewClient class when onPageFinished() method triggered.
         // It means when javascript call traceHTML, showHTML method in DemoJavaScriptInterface class will be triggered immediately.
         mWebView.addJavascriptInterface(new DemoJavaScriptInterface(this),"traceHTML");  
     }  
       
     @Override  
     public boolean onCreateOptionsMenu(Menu menu)   
     {  
         // Inflate the menu; this adds items to the action bar if it is present.  
         getMenuInflater().inflate(R.menu.main, menu);  
         return true;  
     }  
   
     @Override  
     public boolean onOptionsItemSelected(MenuItem item)   
     {
         int id = item.getItemId(); 

         // Trigger & Start to load web page
         if (id == R.id.action_html)
         {
             if(mPageLoading)  
             {  
                 mWebView.stopLoading();  
                 mWebView.loadUrl("about:blank");  
             }  
           
             // start to link to url  
             mWebView.loadUrl(mUrl);
             
             return true;  
         }  
         return super.onOptionsItemSelected(item);  
     }  
       
     @Override  
     public void onBackPressed()   
     {  
         // If there is any view history, go back to previous page.
         // Trigger onBackPressed() when there is no history.
         if(mWebView.canGoBack())   
         {  
             mWebView.goBack();  
         }  
         else   
         {  
             super.onBackPressed();  
         }  
     }  
     
     public class MyAppWebViewClient extends WebViewClient   
     {  
         private Context ctx;  
           
         public MyAppWebViewClient(Context ctx)  
         {  
             this.ctx = ctx;  
         }  
           
         @Override  
         public boolean shouldOverrideUrlLoading(WebView view, String url)   
         {
             // Detect the url can be a host link, or not.
             if(Uri.parse(url).getHost() == null)  
             {  
                 if(url.startsWith("tel:"))  
                 {
                     // Go to have a phone call.

                     /*
                     new AlertDialog.Builder(ctx).setTitle("Tel is ")  
                       .setMessage(url)  
                       .setPositiveButton(android.R.string.ok, null)  
                       .setCancelable(false)  
                       .create()  
                       .show();
                     */
                 }  
                 return false;  
             }  
             if(Uri.parse(url).getHost().length() > 0)  
             {  
                 view.loadUrl(url);  
                 return true;  
             }  
             return false;  
         }  
       
         @Override  
         public void onPageStarted(WebView view, String url, Bitmap facIcon)   
         {  
             // start progress bar  
             mPageLoading = true;  
             mProgress.setVisibility(View.VISIBLE);  
             mProgress.setProgress(0);  
         }  
   
         @Override  
         public void onPageFinished(WebView view, String url)   
         {  
             // stop progress bar  
             mProgress.setVisibility(View.GONE);  
             mPageLoading = false;  
             
             // catch the HTML source code via Javascript.  
             mWebView.loadUrl("javascript:window.traceHTML.showHTML('<head>'+ document.getElementsByTagName('html')[0].innerHTML+'</head>');");  
         }  
     }  
       
     final class DemoJavaScriptInterface   
     {  
         private Context ctx;  
           
         public DemoJavaScriptInterface(Context ctx)  
         {  
             this.ctx = ctx;  
         }  
           
         /**  
          * Don't miss the \@JavascriptInterface, it may make everything doesn't work.  
          * @param html  
          */  
         @JavascriptInterface  
         public void showHTML(String html)   
         {  
             new AlertDialog.Builder(ctx).setTitle("HTML codes")  
                 .setMessage(html)  
                 .setPositiveButton(android.R.string.ok, null)  
                 .setCancelable(false)  
                 .create()  
                 .show();  
         }  
     }  
       
     final class MyWebChromeClient extends WebChromeClient   
     {  
         private Context ctx;  
           
         public MyWebChromeClient(Context ctx)  
         {  
             this.ctx = ctx;  
         }  
           
         @Override  
         public void onProgressChanged(WebView view, int progress)    
         {  
             //Make the bar disappear after URL is loaded, and changes string to Loading...  
             setTitle("Loading...");  
             setProgress(progress * 100); //Make the bar disappear after URL is loaded  
          
             mProgress.setProgress(progress);  
          
             // Return the app name after finish loading  
             if(progress == 100)  
             {  
                 setTitle(R.string.app_name);  
             }  
         }  
         

         // This method will be triggered when you call alert() in javascript. It will command android show this alert dialog.
         @Override  
         public boolean onJsAlert(WebView vw, String url, String msg, JsResult ret)  
         {  
            new AlertDialog.Builder(((Activity)ctx))  
                    .setTitle( "Alert" )  
                    .setMessage( msg )  
                    .setPositiveButton( android.R.string.ok, null )  
                    .setCancelable( false )  
                    .create()  
                    .show();  
             ret.confirm();  
             return true;  
         }  
     }  
 }  


Then the xml of layout as below

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"  
   android:layout_height="match_parent" >  
   
   <WebView android:id="@+id/webview"  
      android:layout_width="match_parent"  
      android:layout_height="match_parent" />  
     
   <ProgressBar android:id="@+id/progressbar"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_alignParentStart="true"  
     android:layout_alignParentLeft="true"  
     android:padding="0dp"  
     android:layout_margin="0dp"  
     style="?android:attr/progressBarStyleHorizontal"  
     android:max="100"  
     android:progress="0"/>  
   
 </RelativeLayout>  



留言

這個網誌中的熱門文章

7-ELEVEN 電子發票明細查詢方式

Java 使用 regular expression 正則表達,過濾特殊字元,反斜線處理重點

Ubuntu GUI中,無法啟動WIFI連結解決方法