Komunikacja między Android Java i PhoneGap Javascript?

Uważam, że możliwe jest wywoływanie metod Javy z (PhoneGap) Javascript.

Ktoś wie jak to zrobić?? (Wiem, jak to zrobić, zmieniając kod źródłowy PhoneGap, ale unikałbym tego)

Author: zorglub76, 2010-04-28

6 answers

W końcu się udało.

  • Utwórz klasę z metodami, których chcesz użyć:

    public class MyClass {
      private WebView mAppView;
      private DroidGap mGap;
    
      public MyClass(DroidGap gap, WebView view)
      {
        mAppView = view;
        mGap = gap;
      }
    
      public String getTelephoneNumber(){
        TelephonyManager tm = 
          (TelephonyManager) mGap.getSystemService(Context.TELEPHONY_SERVICE);
        String number = tm.getLine1Number();
        return number;
      }
    }
    
  • W głównej aktywności Dodaj interfejs Javascript dla tej klasy:

    public class Main extends DroidGap
    {
        private MyClass mc;
    
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            super.init();
    
            mc = new MyClass(this, appView);
            appView.addJavascriptInterface(mc, "MyCls");
    
            super.loadUrl(getString(R.string.url));
        }
    }
    
  • W oknie wywołania Javascript.Metody MyCls:

    <script>
      $(function(){
        $("#phone").text("My telephone number is: " + 
                window.MyCls.getTelephoneNumber());
      });
    </script>
    

Uwaga:

Jak wspomniano w komentarzu, dla Androida w wersji 4.2 i powyżej, dodaj @JavascriptInterface do metody, do której chcesz uzyskać dostęp ze strony HTML. odniesienie .

 124
Author: zorglub76,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:17:08

addJavaScriptInterface(mc, "MyCls") bez luki init() ed może spowodować zmiażdżenie aplikacji, lepiej dodaj super.init() przed addJavascriptInterface()

public class Main extends DroidGap
{
   private MyClass mc;

   @Override
   public void onCreate(Bundle savedInstanceState)
   {
       super.onCreate(savedInstanceState);

       super.init();

       mc = new MyClass(this, appView);
       appView.addJavascriptInterface(mc, "MyCls");

       super.loadUrl(getString(R.string.url));
   }
}
 14
Author: Karfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-02 06:13:39

PhoneGap ma przyzwoity interfejs API wtyczek. Napisałbyś wtyczkę w Javie implementując interfejs IPlugin. Większość magii znajduje się w funkcji execute ().

public interface IPlugin {

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
     */
    PluginResult execute(String action, JSONArray args, String callbackId);

        // ... more ...
}

Najlepszym sposobem na rozpoczęcie pisania wtyczki jest napisanie najpierw javascript API. Można zacząć od napisania niestandardowej klasy javascript, a w każdej metodzie na klasie javascript, dodać zmienne i wywołać wtyczkę opracowaną przy użyciu Phonegap.metoda exec (). Oto podpis metody dla Twojego Referencja.

/* src/com/phonegap/api/PluginManager.java */
/**
 * Receives a request for execution and fulfills it by finding the appropriate
 * Java class and calling it's execute method.
 *
 * PluginManager.exec can be used either synchronously or async. In either case, a JSON encoded
 * string is returned that will indicate if any errors have occurred when trying to find
 * or execute the class denoted by the clazz argument.
 *
 * @param service       String containing the service to run
 * @param action        String containt the action that the class is supposed to perform. This is
 *                      passed to the plugin execute method and it is up to the plugin developer
 *                      how to deal with it.
 * @param callbackId    String containing the id of the callback that is execute in JavaScript if
 *                      this is an async plugin call.
 * @param args          An Array literal string containing any arguments needed in the
 *                      plugin execute method.
 * @param async         Boolean indicating whether the calling JavaScript code is expecting an
 *                      immediate return value. If true, either PhoneGap.callbackSuccess(...) or
 *                      PhoneGap.callbackError(...) is called once the plugin code has executed.
 *
 * @return              JSON encoded string with a response message and status.
 */
@SuppressWarnings("unchecked")
public String exec(final String service, final String action,
    final String callbackId, final String jsonArgs,
    final boolean async)

Musisz również zarejestrować wtyczkę. Możesz to zrobić, dodając kod rejestracyjny na dole niestandardowej biblioteki javascript.

W poniższym przykładzie autor zdefiniował klasę javascript BarcodeScanner i rejestruje ją za pomocą metody addConstructor.

W addConstructor wykonywane są dwa etapy:

  1. Utwórz nową instancję BarcodeScanner w javascript i zarejestruje ją. Jest to dostępne w javascript jako okno.wtyczki.barcodeScanner

  2. Rejestruje niestandardową klasę wtyczki z nazwą usługi. Nazwa usługi jest przekazywany jako pierwszy argument do PhoneGap.exec tak, że PhoneGap może utworzyć instancję klasy wtyczki java i wywołać na niej metodę execute ().

Przykładowy kod rejestracyjny:

PhoneGap.addConstructor(function() {
    /* The following registers an instance of BarcodeScanner in window.plugins.barcodeScanner */
    PhoneGap.addPlugin('barcodeScanner', new BarcodeScanner());

    /* The following associates a service name BarcodeScanner with a class com.beetight.barcodescanner.BarcodeScanner */
    /* The service name is the first argument passed into PhoneGap.exec */
    PluginManager.addService("BarcodeScanner","com.beetight.barcodescanner.BarcodeScanner");
});
 9
Author: Chui Tey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-05-22 08:33:36

Prostsza forma:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.init(); 
    super.appView.getSettings().setJavaScriptEnabled(true);
    super.appView.addJavascriptInterface(this, "MyCls");
    super.loadUrl("file:///android_asset/www/login.html");
}
 6
Author: Heladio Benicio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-26 11:40:29

Jeśli ktoś otrzyma wyjątek nullPointer używając powyższego kodu, zrób super.najpierw oncreate () a potem super..init ()

super.onCreate(savedInstanceState);
super.init();

Znalazłem to rozwiązanie tutaj: Phonegap Google Group

Wielkie dzięki dla @zorglub76 za rozwiązanie....

 5
Author: Dhairya Vora,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-13 06:30:37

Komunikacja z JavaScript do natywnego jest osiągana przez nadpisanie funkcji podpowiedzi JavaScript w macierzystym kodzie Androida, a przekazywana wiadomość jest podobna do tej używanej w systemie iOS. Kiedyś korzystaliśmy z WebView.addJavascriptInterface, aby dodać obiekty Java bezpośrednio do piaskownicy JavaScript, ale powodowało to awarię niektórych urządzeń z Androidem 2.3. Aby wywołać JavaScript z natywnego obecnie używamy WebView.loadUrl ("javascript:..."), ale to ma pewne problemy, więc wkrótce przechodzimy do testowania Javy Kolejka komunikatów wywołująca lokalny serwer HTTP poprzez długotrwałe połączenie XHR.

Opis tutaj

 0
Author: Bodil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-07 09:12:50