2011-09-03 24 views
8

Soy nuevo en PhoneGap y puedo implementar la aplicación básica con PhoneGap, ahora para mejorarla aún más, quiero conectar PhoneGap con actividades de Android, básicamente lo que planeo es llamar método startActivity() usando una función javascript.Cómo llamar a una actividad de Android desde PhoneGap

me trataron Communication between Android Java and Phonegap Javascript?

pero no llamó a una actividad, haciendo que la fuerza error cercano. ¡Ayúdenme, esperando una respuesta!

+1

Publicar registro de errores por favor. –

Respuesta

25

Cualquier llamada de Java de código nativo puede llamar sin utilizar ningún plug-in de la siguiente manera.

Siga los siguientes pasos.

  1. Reemplace el siguiente código con su actividad DroidGap existente.

    @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. Agregue la función personalizada en la actividad actual (esta) de la siguiente manera.

    public void customFunctionCalled() { 
        Log.e("Custom Function Called", "Custom Function Called"); 
    } 
    
  3. Ahora llame a esta función desde su código HTML/JavaScript de la siguiente manera.

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

Para ello, será customFunctionCalled() en MainActivity.

Probado Medio Ambiente Eclipse - 3.7.2 Android 2.2 Emulador PhoneGap - 2.0.0

Por favor envíe sus comentarios aquí para mejorar publicar blogs. http://phonegapexplorers.blogspot.in/2012/08/call-native-java-code-phonegap-android.html

+0

Lo estaba usando desde hace mucho tiempo. Pero recientemente tuve un problema con Android 4.2.2. Aprende de la web que está funcionando correctamente con sdk> = 17. ¿Puedes decirme los cambios que necesito para trabajar con sdk> = 17? – AtanuCSE

+0

@AvtarSingh Suchariya Hy Seguí tu tutorial pero me aparece: 07-08 23: 44: 04.845: Consola web (25296): UnEught TypeError: Object [objeto Object] no tiene el método 'customFunctionCalled' en el archivo: /// android_asset/www/js/index.js: 31 ¿Por qué es eso? Llamé que debe haber algunas modificaciones si el SDK objetivo es 17 o más (creo que es mi caso). Pero no sé cuáles son esos. ¿Podrías ayudarme? –

+0

@AtanuCSE ¿Ha imaginado cómo usar el script con sdk> = 17? ¿Puedes decirme cómo hacerlo? –

2

Es difícil sin saber más acerca de lo que estás tratando de hacer exactamente, pero ir por el camino de escribir un plugin es probablemente el camino a seguir. Revisa;

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

Este plugin podría funcionar para usted como es, o le dará buenos consejos sobre la manera de hacerlo usted mismo.

0

Intento lo que intenta hacer antes, con actualizaciones en phonegap a la versión 2.0.0 y hacia arriba la mejor manera de hacerlo es con el complemento. Esta es la carpeta js en phonegap dentro de los activos. Asegúrese de construir el elemento div con id "nativecall" y un botón de muestra para detectarlo. Asegúrese de ver LogCat para verificar los mensajes de error.

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(); 

en src agregar un nuevo método de clase con el nombre del servicio "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."); 
     } 
    } 
} 
Cuestiones relacionadas