Android Open Source - adkintun-mobile-browser Client






From Project

Back to project page adkintun-mobile-browser.

License

The source code is released under:

Apache License

If you think the Android project adkintun-mobile-browser listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/**
* Copyright 2013 NIC Chile Research Labs
* //from  w ww.  ja  va  2s  .  co  m
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cl.niclabs.adkintunmobile.browser;

import java.net.URI;

import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.TrafficStats;
import android.net.Uri;

/**
 * Clase que implementa los listeners de los eventos de comienzo y trmino de
 * carga de pginas.
 * 
 * @author Sebastin Pereira
 */

public class Client extends WebViewClient {
  /**
   * Instancia de la clase Register, que se encarga de registrar los datos una
   * vez finalizada la carga de la pgina.
   */
  public Register register;
  /**
   * Indica si est cargando una pgina.
   */
  public boolean loading = false;
  /**
   * Indica si se pidi hacer un reload.
   */
  public boolean reloadPending = false;
  private boolean pageStarted = false;
  /**
   * Webview a realizar el reload.
   */
  private CustomWebView webViewToReload;
  /**
   * Pgina actual.
   */
  public String currentPage = "";
  private MainActivity context;
  private long initTime, finishTime;
  private long initBytesReceived, finishBytesReceived;
  private long initBytesSent, finishBytesSent;
  private int myUid;

  /**
   * @param context
   *            Contexto desde el que se usar el cliente.
   */
  public Client(MainActivity context) {
    this.context = context;
    register = new Register(context);
    myUid = android.os.Process.myUid();
  }

  /**
   * Indica si el cliente est cargando una pgina.
   * 
   * @return True si el cliente esta cargando alguna p?gina. False en caso
   *         contrario.
   */
  public boolean isLoading() {
    return loading;
  }

  /**
   * Setea el valor que indica si el browser est cargando una pgina.
   * 
   * @param loading
   *            Indica si el browser est cargando una pgina.
   */
  public void setLoading(boolean loading) {
    this.loading = loading;
  }

  /**
   * Cancela la carga de la pgina actual, si es que se encontraba cargando.
   */
  public void cancelLoad() {
    setLoading(false);
  }

  /**
   * Indica si el cliente tiene un reload pendiente.
   * 
   * @return True si el cliente esta esperando un reload de la pgina actual.
   */
  public boolean isReloadPending() {
    return reloadPending;
  }

  /**
   * Setea el valor que indica si el cliente tiene un reload pendiente.
   * 
   * @param reloadPending
   *            Indica si el cliente tiene un reload pendiente.
   */
  public void setReloadPending(boolean reloadPending) {
    this.reloadPending = reloadPending;
  }

  /**
   * Setea el valor inicial del tiempo, junto con los bytes recibidos y
   * enviados hasta el momento.
   * 
   * @see android.webkit.WebViewClient#onPageStarted(android.webkit.WebView,
   *      java.lang.String, android.graphics.Bitmap)
   */
  @Override
  public void onPageStarted(WebView view, String url, Bitmap favicon) {
    Log.d("AdkinBrowser", "onPageStarted: " + url);
    super.onPageStarted(view, url, favicon);

    context.showTopBar();
    context.showNavigationButtons();
    context.showProgressBar();
    currentPage = url;
    
    InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    im.hideSoftInputFromWindow(context.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    
    if(url.equals(C.defaultStartPageUrl)){
      context.setUrl(C.defaultStartPage);
      return;
    }
    if(UrlUtils.isLocal(url)){
      return;
    }

    if (!isLoading())
      setLoading(true);
    else
      return;// Redireccion
    
    registerPageStarted();

    context.setUrl(url);
    context.updateUI();
  }

  /**
   * Setea los valores de tiempo, bytes enviados y bytes recibidos al momento del inicio de la carga.
   */
  private void registerPageStarted() {
    initTime = System.currentTimeMillis();
    initBytesReceived = TrafficStats.getUidRxBytes(myUid);
    initBytesSent = TrafficStats.getUidTxBytes(myUid);
    pageStarted = true;
  }

  /**
   * Setea el valor final del tiempo, junto con los bytes recibidos y enviados
   * al momento del trmino de la carga. Guarda los datos a travs de la clase
   * Register.
   * 
   * @see android.webkit.WebViewClient#onPageFinished(android.webkit.WebView,
   *      java.lang.String)
   */
  @Override
  public void onPageFinished(WebView view, String url) {
    Log.d("AdkinBrowser", "onPageFinished: " + url);
    context.hideProgressBar();
    context.setUrl(url);
    context.updateUI();
    
    if (url.equals(C.defaultStartPageUrl) || (UrlUtils.isLocal(url))
        || pageStarted == false)
      return;
    
    registerPageFinished();

    String host;
    String TLD;

    try {
      host = (new URI(url)).getHost();
      if(host.lastIndexOf(".") == -1)
        host = "." + host;
    } catch (Exception e) {
      host = ".unknown";
    }
    TLD = host.substring(host.lastIndexOf("."));
    //TLD = url;
    long timeToLoad = finishTime - initTime;
    long bytesSent = finishBytesSent - initBytesSent;
    long bytesReceived = finishBytesReceived - initBytesReceived;

    if (!isLoading() || isReloadPending()) {
      /* Carga interrumpida */
      //(Toast.makeText(view.getContext(), currentPage + "interrupted.", Toast.LENGTH_SHORT)).show();
      register.saveFromBrowser(true, TLD, timeToLoad, bytesSent,
          bytesReceived);
      setLoading(false);
      if (isReloadPending()) {
        webViewToReload.reload();
        setReloadPending(false);
      }
    } else {
      /* Pagina cargada con xito */
      setLoading(false);
      //(Toast.makeText(view.getContext(), currentPage + " succesfully loaded.", Toast.LENGTH_SHORT)).show();
      register.saveFromBrowser(false, TLD, timeToLoad, bytesSent,
          bytesReceived);
    }
    context.updateUI();
  }

  /**
   * Setea los valores de tiempo, bytes enviados y bytes recividos al momento del trmino de la carga.
   */
  private void registerPageFinished() {
    finishTime = System.currentTimeMillis();
    finishBytesReceived = TrafficStats.getUidRxBytes(myUid);
    finishBytesSent = TrafficStats.getUidTxBytes(myUid);
    pageStarted = false;
  }

  /**
   * Implementa protocolos distintos de http y https. Enva un intent para ver
   * si alguna aplicacin del dispositivo puede manejar el protocolo
   * 
   * @see android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,
   *      java.lang.String)
   */
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url != null && !url.startsWith("http")) {
      view.getContext().startActivity(
          new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
      return true;
    } else {
      return false;
    }
  }

  /**
   * Setea la webview pasada como parmetro para que se recargue la URL
   * actual, una vez que se termine la carga previa. Esto se implementa as
   * debido a la naturaleza asncrona de los callbacks (onPageStarted y
   * onPageFinished)
   * 
   * @param webview
   *            Webview a hacer reload.
   */
  public void setReload(CustomWebView webview) {
    this.webViewToReload = webview;
    Log.d("AdkinBrowser", "setReload " + currentPage);
    if (!isLoading()){
      if(!currentPage.equalsIgnoreCase(C.defaultStartPageUrl))
        webview.reload();
      else{
        ((MainActivity)context).navigateToUrl(C.defaultStartPage);
      }
    }else{
      setReloadPending(true);
    }
  }
}




Java Source Code List

cl.niclabs.adkintunmobile.browser.C.java
cl.niclabs.adkintunmobile.browser.Client.java
cl.niclabs.adkintunmobile.browser.CustomWebView.java
cl.niclabs.adkintunmobile.browser.DropDownAnim.java
cl.niclabs.adkintunmobile.browser.FileHandler.java
cl.niclabs.adkintunmobile.browser.MainActivity.java
cl.niclabs.adkintunmobile.browser.PreferencesActivity.java
cl.niclabs.adkintunmobile.browser.Register.java
cl.niclabs.adkintunmobile.browser.UrlUtils.java
cl.niclabs.adkintunmobile.crypto.AESEncrypter.java
cl.niclabs.adkintunmobile.crypto.Encrypter.java
cl.niclabs.adkintunmobile.crypto.RSAEncrypter.java