杰瑞科技汇

PhoneGap、Java与JS如何协同工作?

Of course! This is a great question that gets to the heart of how PhoneGap (now known as Apache Cordova) works. Let's break down the relationship between Java, JavaScript, and PhoneGap.

PhoneGap、Java与JS如何协同工作?-图1
(图片来源网络,侵删)

The short answer is: You primarily write your app's logic in JavaScript, but Java is used to "bridge" your JavaScript code to the native features of the device (like the camera, GPS, or file system).


The Big Picture: How It All Fits Together

Think of PhoneGap as a container. It wraps your web-based code (HTML, CSS, JavaScript) and runs it inside a native shell (a "WebView").

Here's the flow of communication:

  1. Your App (JavaScript): You write your application's user interface (HTML/CSS) and its core logic (JavaScript). This is where you'll spend 95% of your time.
  2. The PhoneGap "Bridge" (Java): When your JavaScript code needs to do something that a web page normally can't (e.g., "take a photo"), it calls a special PhoneGap function.
  3. The Native Device (Java/Kotlin/Swift/Objective-C): This JavaScript call is intercepted by the PhoneGap "bridge," which is a piece of native code. On Android, this code is written in Java (or more recently, Kotlin). This native code then uses the device's official SDK (Software Development Kit) to perform the action (e.g., it calls the Android camera API).
  4. The Result: The native code performs the action and sends the result (e.g., the photo file path) back across the bridge to your JavaScript code, which can then update the UI or process the data.

Detailed Breakdown of Each Component

JavaScript (The Brains of Your App)

This is the most important language for you as a PhoneGap developer. You use it to build the entire user-facing part of your application.

PhoneGap、Java与JS如何协同工作?-图2
(图片来源网络,侵删)
  • What it does:

    • UI Logic: Controls what the user sees and how they interact with it.
    • App Logic: Handles data, calculations, and the overall flow of your application.
    • Calling Native Features: Uses the PhoneGap API (Cordova plugins) to access device hardware.
  • Example: Let's say you want to get the device's current GPS coordinates. In your JavaScript file (www/js/index.js), you would write:

    // Check if the device is ready before trying to get the geolocation
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("Device is ready!");
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    }
    // Success callback
    function onSuccess(position) {
        var element = document.getElementById('geolocation');
        element.innerHTML = 'Latitude: '  + position.coords.latitude      + '<br />' +
                            'Longitude: ' + position.coords.longitude     + '<br />' +
                            '<hr />'      + element.innerHTML;
    }
    // Error callback
    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    In this code, navigator.geolocation is not a standard web browser API. It's a PhoneGap-specific API provided by the "Geolocation" plugin.

Java (The Bridge to the Device)

You will rarely write Java code yourself unless you are creating a custom plugin. Java's role is to act as the translator between your JavaScript world and the native Android world.

PhoneGap、Java与JS如何协同工作?-图3
(图片来源网络,侵删)
  • What it does:

    • Provides the Native Shell: The core PhoneGap project for Android is a standard Android application. The main entry point is a Java class (e.g., MainActivity.java) that sets up the WebView (the component that displays your HTML/JS).
    • Implements Plugin Logic: When you use a plugin like the Camera or Geolocation, the corresponding Java code is executed. For example, when navigator.geolocation.getCurrentPosition() is called, a Java method in the Geolocation plugin is triggered.
    • Handles Communication: This Java code calls the Android OS APIs (e.g., LocationManager) and then passes the result back to the JavaScript layer.
  • Example (Conceptual - you don't write this): Inside the PhoneGap Geolocation plugin, there's a Java class that looks something like this (simplified):

    // This is a conceptual example of the Java plugin code
    public class GeolocationPlugin extends CordovaPlugin {
        @Override
        public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
            if (action.equals("getCurrentPosition")) {
                // 1. Get the Android's LocationManager
                LocationManager lm = (LocationManager) cordova.getActivity().getSystemService(Context.LOCATION_SERVICE);
                // 2. Request location updates from the native API
                // ... code to get location ...
                // 3. Once the location is found, send it back to JavaScript
                Location location = ...; // get the location
                JSONObject result = new JSONObject();
                result.put("latitude", location.getLatitude());
                result.put("longitude", location.getLongitude());
                callbackContext.success(result); // This sends the data back to the JS success callback
                return true;
            }
            return false;
        }
    }

    Notice how this Java code doesn't know anything about your HTML or JavaScript. It just receives a command ("getCurrentPosition"), uses Android's native tools, and sends a result back.

The Role of Other Files

  • config.xml: This is the manifest file for your Cordova app. It's where you declare which plugins your app uses (e.g., <plugin name="cordova-plugin-geolocation" />). It also contains metadata about your app (name, permissions, etc.).
  • package.json: This is a Node.js file that lists your project's dependencies, including all the Cordova plugins you've installed.
  • build.gradle: This is the standard Android build file. Cordova uses it to compile your Java code and package the final Android APK file.

Summary Table

Component Role When You Write It
JavaScript App Logic & UI. The main language for building your application's functionality and user interface. Almost always. This is your primary language as a PhoneGap/Cordova developer.
HTML/CSS Structure & Styling. Defines the content and visual appearance of your app. Almost always. Works alongside JavaScript to create the complete web-based UI.
Java Native Bridge. The "glue" that connects your JavaScript to the underlying Android OS. Rarely. Only if you need to create a custom plugin that accesses an Android feature not already available.
XML (config.xml) Project Configuration. Declares plugins, app permissions, and metadata. Occasionally. When you add a new plugin or change app settings.

Key Takeaway

PhoneGap allows you to use your existing web development skills (HTML, CSS, and especially JavaScript) to build cross-platform mobile applications. The Java part is an internal implementation detail for the Android platform that you don't need to worry about unless you're doing advanced, custom development. The framework handles the complex communication between your JavaScript code and the device's native hardware for you.

分享:
扫描分享到社交APP
上一篇
下一篇