@Override
  /**
   * Initialize the {@link CordovaWebView} and load its start URL.
   *
   * <p>The fragment inflator needs to be cloned first to use an instance of {@link CordovaContext}
   * instead. This alternate context object implements the {@link CordovaInterface} as well and acts
   * as a proxy between the activity and fragment for the {@link CordovaWebView}. The actual {@link
   * CordovaWebView} is defined in the home_view_frag.xml layout and has an id of <b>aemWebView</b>.
   */
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    LayoutInflater localInflater = inflater.cloneInContext(new CordovaContext(getActivity(), this));
    View rootView = localInflater.inflate(R.layout.fragment_jingle, container, false);
    aemView = (CordovaWebView) rootView.findViewById(R.id.jingle_title);
    //      aemView.loadUrl("http://192.168.0.11:8080");
    //        aemView.setWebViewClient(new WebViewClient() {
    //        	public boolean shouldOverrideUrlLoading(WebView view, String url) {
    //        	          view.loadUrl(url);
    //        	          return true;
    //        	           }});
    Config.init(getActivity());
    Config.addWhiteListEntry("http://*", true);
    //      Config.addWhiteListEntry("http://192.168.0.11:8080", true);
    //        aemView.loadUrl("file:///android_asset/md/e/view/viewer.html");
    aemView.getSettings().setJavaScriptEnabled(true);
    aemView.loadUrl("file:///android_asset/demo/index.html");

    //        aemView.loadUrl("http://www.baidu.com");
    return rootView;
  }
 @UiThreadTest
 public void testPreconditions() {
   assertNotNull(innerContainer);
   assertNotNull(testView);
   String url = testView.getUrl();
   assertTrue(url.endsWith("index.html"));
 }
 @Override
 public void onCreate(final Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
   webView = (CordovaWebView) findViewById(R.id.webView);
   webView.loadUrl("file:///android_asset/web/index.html");
 }
  @SuppressWarnings({"deprecation", "ResourceType"})
  protected void createViews() {
    // Why are we setting a constant as the ID? This should be investigated
    webView.getView().setId(1000);
    RelativeLayout.LayoutParams p =
        new RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    webView.getView().setLayoutParams(p);

    if (preferences.contains("BackgroundColor")) {
      int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
      // Background of activity:
      webView.getView().setBackgroundColor(backgroundColor);
    }

    webView.getView().requestFocusFromTouch();
  }
  @Override
  public void initialize(CordovaInterface cordova, CordovaWebView webView) {

    instance = this;
    this.appId = getAppId();
    this.api = WXAPIFactory.createWXAPI(webView.getContext(), this.appId, true);
    this.api.registerApp(this.appId); // 将App注册到微信列表
  }
  /*
   * Sends a json object to the client as parameter to a method which is defined in gECB.
   */
  public static void sendJavascript(JSONObject _json) {
    String _d = "javascript:" + gECB + "(" + _json.toString() + ")";
    Log.v(TAG, "sendJavascript: " + _d);

    if (gECB != null && gWebView != null) {
      gWebView.sendJavascript(_d);
    }
  }
 @Override
 /** The final call you receive before your activity is destroyed. */
 public void onDestroy() {
   super.onDestroy();
   if (cordovaWebView != null) {
     // Send destroy event to JavaScript
     cordovaWebView.handleDestroy();
   }
 }
  /**
   * Create a new plugin result and send it back to JavaScript
   *
   * @param connection status
   */
  private void sendStatusUpdate(boolean isConnected) {
    final Intent intent = new Intent("DatecsPrinter.connectionStatus");

    Bundle b = new Bundle();
    b.putString("userdata", "{ isConnected: " + isConnected + "}");

    intent.putExtras(b);

    LocalBroadcastManager.getInstance(mWebView.getContext()).sendBroadcastSync(intent);
  }
  @Override
  public void onDestroy() {
    super.onDestroy();

    if (this.webView != null) {
      webView.handleDestroy();
    }
    RefWatcher refWatcher = SyngApplication.getRefWatcher(getActivity());
    refWatcher.watch(this);
  }
 @UiThreadTest
 protected void setUp() throws Exception {
   super.setUp();
   testActivity = this.getActivity();
   containerView = (FrameLayout) testActivity.findViewById(android.R.id.content);
   innerContainer = (LinearLayout) containerView.getChildAt(0);
   testView = (CordovaWebView) innerContainer.getChildAt(0);
   testView.loadUrl("file:///android_asset/www/backbuttonmultipage/index.html");
   sleep();
 }
 public void testViaLoadUrl() {
   testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
   sleep();
   String url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample3.html"));
   boolean didGoBack = mUiThread.backHistory();
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   assertTrue(didGoBack);
   didGoBack = mUiThread.backHistory();
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("index.html"));
   assertTrue(didGoBack);
 }
Exemple #12
0
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    LayoutInflater localInflater = inflater.cloneInContext(new CordovaContext(getActivity(), this));
    View rootView = localInflater.inflate(R.layout.fragment_cordova, container, false);
    myWebView = (CordovaWebView) rootView.findViewById(R.id.myWebView);
    myWebView.setBackgroundColor(Color.argb(1, 0, 0, 0));

    // fixes a bug in android 3.0 - 4.0.3 that causes an issue with transparent webviews.
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB
        && android.os.Build.VERSION.SDK_INT
            <= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
      myWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }

    Config.init(getActivity());
    myWebView.loadUrl(Config.getStartUrl());
    return rootView;
  }
 public void testViaHref() {
   testView.sendJavascript("window.location = 'sample2.html';");
   sleep();
   String url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   testView.sendJavascript("window.location = 'sample3.html';");
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample3.html"));
   boolean didGoBack = mUiThread.backHistory();
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   assertTrue(didGoBack);
   didGoBack = mUiThread.backHistory();
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("index.html"));
   assertTrue(didGoBack);
 }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ChromeView.initialize(this);

    setContentView(R.layout.main);

    cordovaWebView = (CordovaWebView) findViewById(R.id.cordovaWebView);

    cordovaWebView.loadUrl("file:///android_asset/www/index.html");
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    loadConfig();
    //
    // ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
    /*
            TODO: it's can be only in activity before adding content and we may need it in Cordova Dapps
            if(!preferences.getBoolean("ShowTitle", false))
            {
                try {
                    getActivity().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
                } catch (Exception e) {
                    System.out.print(e);
                }
            }

            if(preferences.getBoolean("SetFullscreen", false))
            {
                preferences.set("Fullscreen", true);
            }
            if(preferences.getBoolean("Fullscreen", false))
            {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                {
                    immersiveMode = true;
                }
                else
                {
                    getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                }
            } else {
                getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
            }
    */

    //        view = inflater.inflate(R.layout.fragment_web_view, container, false);

    cordovaInterface = makeCordovaInterface();
    if (savedInstanceState != null) {
      cordovaInterface.restoreInstanceState(savedInstanceState);
    }

    init();

    loadUrl();

    //        return view;
    return webView.getView();
  }
 public void testViaBackButtonOnLayout() {
   testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample2.html");
   sleep();
   String url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   testView.loadUrl("file:///android_asset/www/backbuttonmultipage/sample3.html");
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample3.html"));
   BaseInputConnection viewConnection = new BaseInputConnection(containerView, true);
   KeyEvent backDown = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
   KeyEvent backUp = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK);
   viewConnection.sendKeyEvent(backDown);
   viewConnection.sendKeyEvent(backUp);
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("sample2.html"));
   viewConnection.sendKeyEvent(backDown);
   viewConnection.sendKeyEvent(backUp);
   sleep();
   url = mUiThread.getUrl();
   assertTrue(url.endsWith("index.html"));
 }
  private void loadUrl() {
    if (url == null || url.isEmpty()) {
      url = DEFAULT_DAPP;
    }

    if (webView == null) {
      init();
    }

    // If keepRunning
    this.keepRunning = preferences.getBoolean("KeepRunning", true);

    if (url.indexOf("dapp://") == 0) {
      url = url.replace("dapp://", "http://");
    }

    webView.loadUrlIntoView(url, true);
  }
  public Object onMessage(String id, Object data) {
    if ("onReceivedError".equals(id)) {
      // TODO: do we need handle error and show it?
      /*
                  JSONObject d = (JSONObject) data;
                  try {
                      this.onReceivedError(d.getInt("errorCode"), d.getString("description"), d.getString("url"));
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
      */
    } else if ("onPageFinished".equals(id)) {

      webView.getEngine().loadUrl("javascript: " + js_cordova, false);
    } else if ("exit".equals(id)) {
      getActivity().finish();
    }
    return null;
  }
  @Override
  public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
    WebResourceResponse response = super.shouldInterceptRequest(view, url);

    // Already intercepted (e.g. if url is not whitelisted)
    if (response != null) {
      return response;
    }

    // Not a localhost request
    Uri origUri = Uri.parse(url);
    String host = origUri.getHost();
    if (host == null || !host.equals("localhost")) {
      return null;
    }

    // Localhost request
    try {
      String localPath = WWW_DIR + origUri.getPath();
      // Trying to access file outside assets/www
      if (!isFileUnder(localPath, WWW_DIR)) {
        throw new IOException("Trying to access file outside assets/www");
      } else {
        Uri localUri = Uri.parse("file://" + localPath);
        CordovaResourceApi resourceApi = cordovaWebView.getResourceApi();
        OpenForReadResult result = resourceApi.openForRead(localUri, true);
        Log.i(
            "SalesforceIceCreamWebViewClient.shouldInterceptRequest",
            "Loading local file:" + localUri);
        return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream);
      }

    } catch (IOException e) {
      Log.e(
          "SalesforceIceCreamWebViewClient.shouldInterceptRequest",
          "Invalid localhost url:" + url,
          e);
      return new WebResourceResponse("text/plain", "UTF-8", null);
    }
  }
Exemple #20
0
  /**
   * Sets the context of the Command. This can then be used to do things like get file paths
   * associated with the Activity.
   *
   * @param cordova The context of the main Activity.
   * @param webView The CordovaWebView Cordova is running in.
   */
  public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    this.sockMan =
        (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    this.connectionCallbackContext = null;

    // We need to listen to connectivity events to update navigator.connection
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    if (this.receiver == null) {
      this.receiver =
          new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
              // (The null check is for the ARM Emulator, please use Intel Emulator for better
              // results)
              if (NetworkManager.this.webView != null)
                updateConnectionInfo(sockMan.getActiveNetworkInfo());
            }
          };
      webView.getContext().registerReceiver(this.receiver, intentFilter);
    }
  }
  protected void init() {
    webView = makeWebView();
    createViews();
    if (!webView.isInitialized()) {
      webView.init(cordovaInterface, pluginEntries, preferences);
    }
    webView.getView().requestFocusFromTouch();
    cordovaInterface.onCordovaInit(webView.getPluginManager());
    // webView.clearCache();
    android.webkit.CookieManager.getInstance().removeAllCookie();

    // Wire the hardware volume controls to control media if desired.
    String volumePref = preferences.getString("DefaultVolumeStream", "");
    if ("media".equals(volumePref.toLowerCase(Locale.ENGLISH))) {
      getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
    }
    BaseActivity activity = (BaseActivity) getActivity();
    activity.hideToolbar(2);
    gestureDetector = new GestureDetector(webView.getContext(), this);
    webView.getView().setOnTouchListener(this);
  }
 public void testForCordovaView() {
   String className = testView.getClass().getSimpleName();
   assertTrue(className.equals("CordovaWebView"));
 }
 CordovaWebChromeClient(Context context, CordovaWebView view) {
   super((XWalkView) view.getView());
   appView = view;
 }
 private static void fireOnMessage(String payload) {
   webView.sendJavascript("chrome.gcm.onMessage.fire({data:" + payload + "})");
 }
 private static void fireOnMessagesDeleted(String payload) {
   webView.sendJavascript("chrome.gcm.onMessagesDeleted.fire()");
 }
  @Override
  public void setUp() throws Exception {

    if (testResults == null || !testResults.containsKey(jsSuite)) {
      if (testResults == null) {
        testResults = new HashMap<String, Map<String, TestResult>>();
      }

      if (!testResults.containsKey(jsSuite)) {
        testResults.put(jsSuite, new HashMap<String, TestResult>());
      }

      // Wait for app initialization to complete
      EventsListenerQueue eq = new EventsListenerQueue();
      if (!SalesforceSDKManager.hasInstance()) {
        eq.waitForEvent(EventType.AppCreateComplete, 5000);
      }

      // Start main activity
      Instrumentation instrumentation = getInstrumentation();
      final Intent intent = new Intent(Intent.ACTION_MAIN);
      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setClassName(
          instrumentation.getTargetContext(),
          SalesforceSDKManager.getInstance().getMainActivityClass().getName());
      SalesforceDroidGapActivity activity =
          (SalesforceDroidGapActivity) instrumentation.startActivitySync(intent);

      // Block until the javascript has notified the container that it's ready
      TestRunnerPlugin.readyForTests.take();

      // Now run all the tests and collect the resuts in testResults
      for (String testName : getTestNames()) {
        final String jsCmd =
            "javascript:"
                + "navigator.testrunner.setTestSuite('"
                + jsSuite
                + "');"
                + "navigator.testrunner.startTest('"
                + testName
                + "');";
        final CordovaWebView appView = activity.getAppView();
        if (appView != null) {
          appView
              .getView()
              .post(
                  new Runnable() {
                    @Override
                    public void run() {
                      appView.loadUrl(jsCmd);
                    }
                  });
        }
        Log.i(getClass().getSimpleName(), "running test:" + testName);

        // Block until test completes or times out
        TestResult result = null;
        int timeout = getMaxRuntimeInSecondsForTest(testName);
        try {
          result = TestRunnerPlugin.testResults.poll(timeout, TimeUnit.SECONDS);
          if (result == null) {
            result =
                new TestResult(
                    testName, false, "Timeout (" + timeout + " seconds) exceeded", timeout);
          }
        } catch (Exception e) {
          result = new TestResult(testName, false, "Test failed", timeout);
        }
        Log.i(getClass().getSimpleName(), "done running test:" + testName);

        // Save result
        testResults.get(jsSuite).put(testName, result);
      }

      // Cleanup
      eq.tearDown();
      activity.finish();
    }
  }
 private static void fireOnSendError(String payload) {
   String mid = "1";
   String mtext = payload;
   webView.sendJavascript(
       "chrome.gcm.onSendError.fire({messageId:'" + mid + "', errorMessage:'" + mtext + "'})");
 }