Getting Started: WebView-based Applications for Web Developers

Getting started with the Android WebView is fairly simple, whether you want load a remote URL or display pages stored in your app.

This tutorial walks you through creating a new Android Project, adding a WebView, loading a remote URL, and then loading a local HTML page.

Note: This tutorial assumes you're a developer with limited or no experience with the Android development environment, but have some experience with Java. If you're already familiar with programming for Android, you may want to refer to to Building Web Apps in WebView on the Android developer site instead.

This tutorial uses Android Studio, the new design-and-build IDE for Android. So you'll need start off by installing Android Studio, as described here:

http://developer.android.com/sdk/installing/studio.html

When the installation completes, Android Studio launches and displays the welcome screen.

To create a new project:

  1. Click New Project.
  2. On the next page, enter your application name, package name and target SDKs, and click Next.

    Note: If you only intend to support the Chromium WebView (rather than the old WebKit WebView) set Minimum required SDK to API 19: Android 4.4 (KitKat).

  3. On the next page, you're prompted to enter an application icon. (You can change the icon later, so don't worry if you don't have one right now.) When you're done, click Next.

  4. The next page lets you select the main Android activity for your application. For the purposes of this guide, select Blank Activity and click Next.

    Note: An Android Activity can be viewed as a screen of an app. In this case, the application's main activity will hold the web view. If you're planning to venture further into native Android development, you can find more information in the Android Activities API guide

  5. The next page lets you change the names for the default Activity and layout. Click Finish to accept the defaults and create the project.

    You now have a new Android project. Next, to add the WebView!

Note: After you have your project created, make sure you have the KitKat SDK installed. Go to Tools > Android > SDK Manager and make sure you have Android 4.4 (API 19) installed.

Android Studio will give you some boilerplate code to set up your application. Your project's structure should look something like this:

A few of the more import folders are identified in the picture:

  1. src/main/java. Android Java source code.
  2. src/main/res. Resources used by the native application.
  3. src/main/res/drawable-type. Image resources used by the native application.
  4. src/main/res/layout. XML layout files that define the structure of UI components.
  5. src/main/res/values. Dimensions, strings, and other values that you might not want to hard-code in your application.
  6. src/main/AndroidManifest.xml. The manifest file defines what's included in the application: activities, permissions, themes, and so on.

You need to add a WebView to the main activity's layout.

  1. Open the activity_main.xml file in the src/main/res/layout directory if it is not already open. (You may also see a fragment_main.xml file. You can ignore this, as it's not required for this tutorial.)

    Select the Text tab at the bottom of the of the activity_main.xml editor to see the XML markup.

    This file defines the layout for your main activity, and the Preview panes show the a preview of the activity. The Blank Activity layout doesn't include any children. You'll need to add the WebView.

  2. In the XML pane, remove the self-closing slash from the end of the FrameLayout element, and add the <WebView> element and a new closing tag, as shown:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:id="@+id/container"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context=".MainActivity">
         tools:ignore="MergeRootFrame">
         
             <WebView
             android:id="@+id/activity_main_webview"
             android:layout_width="match_parent"
             android:layout_height="match_parent" />
    </FrameLayout>
  3. To use the WebView you need to reference it in the Activity. Open the Java source file for the main activity, MainActivity.java in the src/main/java/<PackageName> directory.

    Add the lines shown in bold.

    public class MainActivity extends Activity {
        
        private WebView mWebView;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            mWebView = (WebView) findViewById(R.id.activity_main_webview);
    

    The existing code in the onCreate method does the work of hooking up the Activity with the layout. The added lines create a new member variable, mWebView, to refer to the web view.

    Remove the following code:

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment())
            .commit();
    }

    The WebView is identified by the resource ID, which is specified by this line in the layout file:

    android:id="@+id/activity_main_webview"

    After adding the code, you'll see some warning messages in the margin of the editor. This is because you haven't imported the right classes for WebView. Luckily Android Studio can help you fill in the missing classes. The easiest way to do this is click and hover over an unknown class name and wait for a popup showing a "quick fix" -- in this case, adding an import statment for the WebView class.

    Press Alt + Enter (Option + Enter on Mac) to accept the quick fix.

    경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
    어린이용이며, 설치가 필요없는 브라우저 게임입니다.
    https://s1004games.com

    WebView in hand you can move on to setting it up and and loading some juicy web content.

WebViews don't allow JavaScript by default. To run a web application in the web view, you need to explicitly enable JavaScript by adding the following lines to the onCreate method:

// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

If you're going to load data from a remote URL, your application needs permission to access the internet. This permission needs to be added in the application's manifest file.

  1. Open the AndroidManifest.xml file in the src/res directory. Add the line in bold before the closing </manifest> tag.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest ...>
    ...
     
        </application>
        
        <uses-permission android:name="android.permission.INTERNET" />
        
    </manifest>
  2. The next step is to call the loadUrl method on the webview. Add the following line to the end of the onCreate method.

    mWebView.loadUrl("http://beta.html5test.com/");

    Now try running the project. If you don't have a device handy, you can create an emulator (AVD or Android Virtual Device) by going to Tools >Android > AVD Manager.

Note: To detect when a URL has started and finished loading, use WebViewClient.onPageStarted and WebViewClient.onPageFinished.

Now try changing the URL you're loading to http://www.html5rocks.com/ and rerun your application. You'll notice something strange.

If you run the application now with a site that has a redirect like html5rocks.com, your app ends up opening the site in a browser on the device, not in your WebView -- probably not what you expected. This is because of the way the WebView handles navigation events.

Here's the sequence of events:

  1. The WebView tries to load the original URL from the remote server, and gets a redirect to a new URL.
  2. The WebView checks if the system can handle a view intent for the URL, if so the system handles the URL navigation, otherwise the WebView will navigate internally (i.e. the user has no browser installed on their device).
  3. The system picks the user's preferred application for handling an http:// URL scheme -- that is, the user's default browser. If you have more than one browser installed, you may see a dialog at this point.
browser selection dialog

If you're using a WebView inside an Android application to display some simple web content (for example, a help page), this may be exactly what you want to do. However, for more sophisticated applications, you may want to handle the navigation links yourself.

To handle navigation inside the WebView you need to override the WebView's WebViewClient, which handles various events generated by the WebView. You can use it to control how the WebView handles link clicks and page redirects.

The default implementation of WebViewClient makes any URL open in the WebView:

// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());

This is a good step forward, but what if you want to handle links for your site only, while opening other URLs in a browser?

To achieve this you need to extend the WebViewClient class and implement the shouldOverrideUrlLoading method. This method is called whenever the WebView tries to navigate to a different URL. If it returns false, the WebView opens the URL itself. (The default implementation always returns false, which is why it works in the previous example.)

Create a new class:

  1. Right-click the package name of your app and select New > Java Class
  2. Enter MyAppWebViewClient as the class name and click OK
  3. In the new MyAppWebViewClient.java file, add the following code (changes shown in bold):

    public class MyAppWebViewClient extends WebViewClient {
            
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(Uri.parse(url).getHost().endsWith("html5rocks.com")) {
                    return false;
                }
                 
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                view.getContext().startActivity(intent);
                return true;
            }
        }

    The new code defines MyAppWebViewClient as a subclass of WebViewClient and implements the shouldOverrideUrlLoading method.

    The shouldOverrideUrlLoading method is called whenever the WebView is about to load a URL. This implementation checks for the String "html5rocks.com" at the end of the host name of the URL. If the string exists, the method returns false, which tells the platform not to override the URL, but to load it in the WebView.

    For any other hostname, the method makes a request to the system to open the URL. It does this by creating a new Android Intent and using it to launch a new activity. Returning true at the end of the method prevents the URL from being loaded into the WebView.

  4. To use your new custom WebViewClient, add the following lines to your MainActivity class:

    // Stop local links and redirects from opening in browser instead of WebView
        mWebView.setWebViewClient(new MyAppWebViewClient());
        

    Now, a user can click any of the HTML5Rocks links and stay within the app, but links to external sites are opened in a browser.

As you start playing around and navigating the awesome HTML5Rocks articles, hitting the back button on Android exits the application, even though you've explored a few pages of the site.

WebView has a method canGoBack which tells you if there is anything on the page stack that can be popped. All you need to do is detect a back button press and determine if you should step back through the WebView's history or allow the platform to determine the correct behaviour. Inside your MainActivity class, add the following method (in bold):

public class MainActivity extends Activity {
   
 private WebView mWebView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     ...
 }
   
    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       ...
    }
    
}

A big advantage of using a WebView inside an installable application is that you can store assets inside the app. This lets your app work offline and improves load times, since the WebView can retrieve assets directly from the local file system.

To store files such as HTML, JavaScript, and CSS locally, put them in the assets directory. This is a reserved directory that Android uses for raw files that your app may need access to (i.e. files it knows it should minimise or compress).

In your project, create the assets directory in main (src/main/assets).

Generally it's good practice to keep your web files in a subdirectory, so create a www directory and put all your web content in it.

Note: Absolute paths do not work in the WebView when referring to other files, such as CSS and JavaScript. So make sure you make all references relative, instead of absolute (for example, instead of "/pages/somelink.html", use "./pages/somelink.html").

Once you have everything in your assets directory, it's as simple as loading in the appropriate file:

mWebView.loadUrl("file:///android_asset/www/index.html");

You'll want to tweak the shouldOverrideUrlLoading method so it opens a browser for non-local pages:

public class MyAppWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if(Uri.parse(url).getHost().length() == 0) {
            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }

}

Now you are set to build a great WebView app!

For tips on getting the visuals just right, see Pixel-Perfect UI in the WebView.

If you run into trouble, the Chrome DevTools are your friends. See Remote Debugging on Android to get started.

 

[출처] https://developer.chrome.com/multidevice/webview/gettingstarted

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
101 나인패치(Nine Patch) 이미지란? file 졸리운_곰 2020.10.10 54
100 Python으로 안드로이드 앱 만들기 졸리운_곰 2020.09.30 839
99 [Android] Fragment 를 이용한 탭 만들기 file 졸리운_곰 2020.09.19 52
98 빠르게배우는 안드로이드 Fragment-4(Fragment간 에 데이터전달) file 졸리운_곰 2020.09.19 36
97 빠르게배우는 안드로이드 Fragment-3(Fragment기초 실습) file 졸리운_곰 2020.09.19 58
96 빠르게배우는 안드로이드 Fragment-2(Activity-> Fragment로 쉽게 변경) 졸리운_곰 2020.09.19 38
95 빠르게배우는 안드로이드 Fragment -1 (배경) file 졸리운_곰 2020.09.19 38
94 안드로이드 스튜디오 - 새로 생성한 Activity Class를 쉽게 Manifest에 등록하기. file 졸리운_곰 2020.08.08 52
93 Android Studio Build시 failed linking references 해결방법 file 졸리운_곰 2020.05.05 517
92 [안드로이드 스튜디오] COULD NOT FIND COM.ANDROID.TOOLS.BUILD:GRADLE:3.0.0-BETA6 file 졸리운_곰 2020.05.05 43
91 Android Sync SQLite Database with Server using PHP and MySQL file 졸리운_곰 2019.02.25 7403
90 안드로이드의 MVC, MVP, MVVM 종합 안내서 file 졸리운_곰 2019.01.06 256
» Getting Started: WebView-based Applications for Web Developers file 졸리운_곰 2018.09.03 264
88 App Inventor - MySQL interface 앱 인벤터 mysql 연결 file 졸리운_곰 2018.04.07 2330
87 Connect App Inventor to MySQL Database 앱 인벤터와 mysql 데이터베이스 연결 file 졸리운_곰 2018.04.07 5385
86 Create an API (PHP) 앱 인벤터와 php 통합 file 졸리운_곰 2018.04.07 493
85 Android WebView javascriptInterface 사용하기 file 졸리운_곰 2018.03.26 497
84 Using the WebViewer Control in App Inventor 앱인터에서 웹뷰 컨트롤 사용 file 졸리운_곰 2018.03.24 390
83 WebView Javascript Processor for App Inventor 앱 인벤터 웹뷰 자바스크립트 인터페이스 file 졸리운_곰 2018.03.24 365
82 android webview로 javascript 호출 및 이벤트 받기(연동하기) file 졸리운_곰 2018.03.19 1299
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED