javascript 如何从 PhoneGap 调用 Android Activity

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7292553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:37:11  来源:igfitidea点击:

How to call an Android Activity from PhoneGap

javascriptandroidcordovaandroid-activity

提问by Aditya Gaykar

I am new to PhoneGap and I am able to implement the basic app with PhoneGap, now to enhance it further, I want to connect PhoneGap with Android Activities, basically what I plan is to call startActivity() method using a javascript function.

我是 PhoneGap 的新手,我能够使用 PhoneGap 实现基本应用程序,现在为了进一步增强它,我想将 PhoneGap 与 Android 活动连接起来,基本上我的计划是使用 javascript 函数调用 startActivity() 方法。

I tried Communication between Android Java and Phonegap Javascript?

我试过Android Java 和 Phonegap Javascript 之间的通信?

but I failed to call an activity, causing force close error. Do help me out, awaiting a reply!

但我未能调用活动,导致强制关闭错误。帮帮我,等待回复!

回答by AvtarSingh Suchariya

Any Java Native code call be called without using any plugin as following.

任何 Java Native 代码调用都可以在不使用任何插件的情况下调用,如下所示。

Follow The following Steps.

请按照以下步骤操作。

  1. Replace the following code with your existing DroidGap Activity.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init(); // Calling this is necessary to make this work
        appView.addJavascriptInterface(this, "MainActivity");
    
        /* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
    
        super.loadUrl("file:///android_asset/www/index.html");
    }
    
  2. Add the custom function in current (this) activity as following.

    public void customFunctionCalled() {
        Log.e("Custom Function Called", "Custom Function Called");
    }
    
  3. Now call this function from your HTML/JavaScript code as following.

    <script type="text/javascript">
        function callNewActivity() {
            window.MainActivity.customFunctionCalled();
        }
    </script>
    
  1. 将以下代码替换为您现有的 DroidGap 活动。

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.init(); // Calling this is necessary to make this work
        appView.addJavascriptInterface(this, "MainActivity");
    
        /* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
    
        super.loadUrl("file:///android_asset/www/index.html");
    }
    
  2. 在当前(此)活动中添加自定义函数,如下所示。

    public void customFunctionCalled() {
        Log.e("Custom Function Called", "Custom Function Called");
    }
    
  3. 现在从您的 HTML/JavaScript 代码调用此函数,如下所示。

    <script type="text/javascript">
        function callNewActivity() {
            window.MainActivity.customFunctionCalled();
        }
    </script>
    

This will call customFunctionCalled()in MainActivity.

这将调用customFunctionCalled()MainActivity

Tested Environment Eclipse - 3.7.2 Android 2.2 Emulator PhoneGap - 2.0.0

测试环境 Eclipse - 3.7.2 Android 2.2 模拟器 PhoneGap - 2.0.0

Please provide your comments here to improve blogs post. http://phonegapexplorers.blogspot.in/2012/08/call-native-java-code-phonegap-android.html

请在此处提供您的意见以改进博客文章。 http://phonegapexplorers.blogspot.in/2012/08/call-native-java-code-phonegap-android.html

回答by Mike P

Its hard without knowing more about what you're trying to do exactly, but going down the road of writing a plugin is probably the way to go. Check out;

如果不了解更多关于您想要做什么的确切信息,这很难,但是沿着编写插件的道路走下去可能是要走的路。查看;

http://smus.com/android-phonegap-plugins

http://smus.com/android-phonegap-plugins

This plugin might work for you as is, or give you good pointers in how to do this yourself.

这个插件可能会按原样为您工作,或者为您提供有关如何自己执行此操作的良好指示。

回答by Jaiprakash Soni

Try creating plugins, here are some plugins example https://github.com/phonegap/phonegap-plugins

尝试创建插件,这里有一些插件示例 https://github.com/phonegap/phonegap-plugins

回答by syarul

I try what you trying to do before, with updates on phonegap to version 2.0.0 and upward the best way to do is with plugin. This is the js on phonegap within assets folder. Make sure to construct div element with id "nativecall" and a sample button to do detect it.Be sure to watch LogCat to check error messages.

我尝试了您之前尝试做的事情,将 phonegap 更新到 2.0.0 及更高版本,最好的方法是使用插件。这是assets文件夹中phonegap上的js。确保构造 id 为“nativecall”的 div 元素和一个示例按钮来检测它。确保观看 LogCat 以检查错误消息。

    window.echo = function(str, callback) {
    cordova.exec(callback, function(err) {
        callback('Nothing to echo.');
    }, "Echo", "echo", [str]);
};

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function() {

        var abiter = $('#nativecall').html();

            $("#abutton").click(function () {
                    window.echo(abiter, function(echoValue) {
                    alert(echoValue = abiter); // should alert true.
                });
            });


    }
};

app.initialize();

on src add new class method with service name "Echo".

在 src 上添加服务名称为“Echo”的新类方法。

    package org.apache.cordova.plugin;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.plugin.AndroidActivities;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

/**
 * This class echoes a string called from JavaScript.
 */
public class Echo extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("echo")) {
            String message = args.getString(0);
            new AndroidPublicFunction(message); //call function from AndroidActivities
            this.echo(message, callbackContext);
            return true;
        }
        return false;
    }

    private void echo(String message, CallbackContext callbackContext) {
        if (message != null && message.length() > 0) { 
            callbackContext.success(message);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}