Use HTML5 to develop Android local applications (1)

Source: Internet
Author: User
Tags call back drawtext

HTML5 is one of the most popular technologies. The WebKit browser provided by Android has good support for HTML5.And the latest versions of various browsers have begun to support HTML5. There are two main advantages of using HTML5 to develop mobile apps: OneApplications can be used across platforms, including different mobile platforms and PCs. Second, applications can be downloaded from the server, but not dependent on the background Serv.Er can also be run to better combine Web applications with local applications.

 

The purpose of this series of articles is to study and experiment the advantages and disadvantages and feasibility of using HTML5 to develop Android local applications, including HTAdvantages and limitations of Ml5, interaction between webpage and application environment, and how we can control and modify browser plug-ins,It is better integrated with the mobile phone environment.

 

First, embed a webview into the application interface, establish its interaction with the environment, and load a simple HTML5 page.You can use URL "file: // android_asset/index.html" to load the HTML file to be loaded in the asset directory. The function of this page is to use caNvas draws a simple image.

 

String path = "file:///android_asset/index.html";String TAG = "WebClientDemo";boolean isLoadResources = true;WebView mWebView;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.webview1);init();mWebView.loadUrl(path);}

 

Initialize webview, set parameters, the key is to set language for UTF-8 and ensure support for Javascript

 

mWebView = (WebView) findViewById(R.id.myWebView1);mWebView.setBackgroundColor(Color.WHITE);mWebView.getSettings().setDefaultTextEncodingName("UTF-8");mWebView.getSettings().setSupportZoom(true);mWebView.getSettings().supportMultipleWindows();mWebView.getSettings().setJavaScriptEnabled(true);mWebView.clearView();

 

Webviewclient intercepts and modifies various events during webpage loading. First, set a newAnd then rewrite the shouldoverrideurlloading function. Do thisThe reason is that when you click the URL link in the webview plug-in, the page is still displayed in the webview plug-in, instead of callingUse the system's Web browser.

 

mWebView.setWebViewClient(new WebViewClient() {// Intercepts url loadingpublic boolean shouldOverrideUrlLoading(WebView view, String url) {view.loadUrl(url);return true;}                                                ...                }

 

The following code intercepts and modifies other event behaviors in webviewclient. The intercepted events in the example code includeBefore a page is loaded, it contains errors, repeated submission, and resource loading. For example, when a webpage error occurs, you can use your own error information instead of browsing.Plug-in error message.

 

// Intercepts the resource loading events @ overridepublic void onloadresource (webview view, string URL) {If (! Isloadresources) {log. I (TAG, "block resource loading:" + URL); return;} else {log. I (TAG, "Continue resource loading:" + URL); super. onloadresource (view, URL) ;}// intercepts error messagepublic void onreceivederror (webview view, int errorcode, string description, string failingurl) {log. I (TAG, failingurl); toast. maketext (activity, "webpage error:" + errorcode + "webpage unavailable", toast. length_long ). show () ;}// intercepts form resubmissionpublic void onformresubmission (webview view, message dontresend, message resend) {log. I (TAG, "resubmission"); toast. maketext (activity, "repeated submission is not allowed. Press back to return to the upper-level webpage", toast. length_short ). show () ;}// intercepts page started eventpublic void onpagestarted (webview view, string URL, bitmap favicon) {log. I (TAG, "page load start");} // intercepts page finished eventpublic void onpagefinished (webview view, string URL) {log. I (TAG, "page load finish ");}

 

In webview, when you press the back key, you need to call back in webview to access the history page. When there is no history pageThe system prompts whether to exit.

The onkeydown function must be rewritten in the current activity to process the back event.

 

public boolean onKeyDown(int keyCode, KeyEvent event) {// Forwards the back key event to browser pluginif ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {String url;mWebView.goBack();return true;}// Pops up a dialog before exitif ((keyCode == KeyEvent.KEYCODE_BACK) && (!mWebView.canGoBack())) {new AlertDialog.Builder(this).setTitle(R.string.title).setMessage(R.string.quit_desc).setNegativeButton(R.string.cancel,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int which) {}}).setPositiveButton(R.string.confirm,new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog,int whichButton) {android.os.Process.killProcess(android.os.Process.myPid());}}).show();return true;}return super.onKeyDown(keyCode, event);}

 

Webchromeclient is responsible for processing Javascript dialogs, website icons, and loading progress bars. The followingCode to add a progress bar for loading webpages on the Activity

 

mWebView.setWebChromeClient(new WebChromeClient() {public void onProgressChanged(WebView view, int progress) {activity.setProgress(progress * 100);}});

 

Exit prompt box

 

 

 

HTML5 Display Effect and Page code:

 

  <script type="application/x-javascript">    function drawText() {      var canvas = document.getElementById("canvas");      if (canvas.getContext) {        var ctx = canvas.getContext("2d");        var message = "First HTML5 page"        ctx.fillStyle = "#FF0000";        ctx.font = "30px serif";var xPosition = 20;var yPosition = 30;                ctx.fillText (message,xPosition,yPosition);      }    }  </script> <body onload="drawText();">   <canvas id="canvas" width="300" height="300"></canvas> </body>

 

 

 

In future articles, we will discuss other HTML5 functions and application methods on mobile phones.

From: http://community-china.developer.motorola.com/t5/MOTODEV-%E5%8D%9A%E5% AE %A2/%E4%BD%BF%E7%94%A8HTML5%E5%BC%80%E5%8F%91Android%E6%9C%AC%E5%9C%B0%E5%BA%94%E7%94%A8-%E4%B8%80/ba-p/1742

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.