Android Open Source - adkintun-mobile-browser Main Activity






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
* //w  w w.  j  a  va2s  . c  o 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.io.IOException;
import java.io.InputStream;


import cl.niclabs.adkintunmobile.browser.R;

import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.ProgressBar;

/**
 * Actividad principal del browser. Despliega la interfaz de navegacin e
 * implementa su funcionalidad (botones, input de URL, etc).
 * 
 * @author Sebastin  Pereira
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
  private CustomWebView browser;
  private AutoCompleteTextView urlEditText;
  TextWatcher mUrlTextWatcher;
  private ImageButton goBtn;
  private ImageButton backBtn;
  private ImageButton forwardBtn;
  private int navButtonHeight;
  private ProgressBar progressBar;
  private View topBar;
  private int topBarHeight;
  private Client webViewClient;
  private String prevUrl;
  private OnTouchListener clearTextListener;
  public boolean topBarJustShown = false;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String homeURL = PreferenceManager.getDefaultSharedPreferences(this).getString("homeURL", C.defaultStartPage);

    setContentView(R.layout.activity_main);
    webViewClient = new Client(this);
    prevUrl = "";

    urlEditText = (AutoCompleteTextView) findViewById(R.id.inputURL);
    browser = (CustomWebView) findViewById(R.id.browser);
    goBtn = (ImageButton) findViewById(R.id.goBtn);
    backBtn = (ImageButton) findViewById(R.id.backBtn);
    forwardBtn = (ImageButton) findViewById(R.id.forwardBtn);
    navButtonHeight = backBtn.getLayoutParams().height;
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    topBar = (View) findViewById(R.id.topBar);
    topBarHeight = topBar.getLayoutParams().height;

    setBrowserSettings();
    setGoButton();
    setBackButton();
    setForwardButton();
    setUrlEditText();
    setClearText();
    setUrl(homeURL);
    
    Intent i = getIntent();
        if (i.getData() != null) {
          // App first launch from another app.
          navigateToUrl(i.getDataString());
        }else{
          navigateToUrl(homeURL);
        }
        
        TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String deviceID = mTelephonyManager.getDeviceId();
      FileHandler.tryUpload(deviceID, this);
  }

  /**
   * Setea la configuracin del navegador.
   */
  private void setBrowserSettings() {
    browser.setWebViewClient(webViewClient);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setRenderPriority(RenderPriority.HIGH);
    browser.getSettings().setNeedInitialFocus(false);
    browser.getSettings().setUseWideViewPort(true);
    
    browser.setWebChromeClient(new WebChromeClient() {
      public void onProgressChanged(WebView view, int progress) {
        progressBar.setProgress(progress);
        if (progress == 100 && !urlEditText.isFocused()){
          hideProgressBar();
        }
      }
    });
  }

  /**
   * Setea la funcionalidad del botn 'ir'
   */
  private void setGoButton() {
    goBtn.setOnClickListener(new OnClickListener() {
      public void onClick(View btn) {
        if (webViewClient.isLoading()) {
          webViewClient.setLoading(false);
          webViewClient.setReloadPending(false);
          browser.stopLoading();
          updateUI();
          return;
        }
        String newUrl = urlEditText.getText().toString();
        if (browser.getUrl() != null && (browser.getUrl()).equals(newUrl)) {
          webViewClient.setReload(browser);
          Log.d("AdkinBrowser", "Reloading " + newUrl);
          updateUI();
        } else {
          navigateToUrl(newUrl);
          updateUI();
        }
      }
    });
  }
  
  /**
   * Setea la funcionalidad del botn 'back'
   */
  private void setBackButton() {
    backBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
              webViewClient.setLoading(false);
        webViewClient.setReloadPending(false);
        browser.stopLoading();
            browser.goBack();
            }          
        });
  }
  
  /**
   * Setea la funcionalidad del botn 'forward'
   */
  private void setForwardButton() {
    forwardBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
              webViewClient.setLoading(false);
        webViewClient.setReloadPending(false);
        browser.stopLoading();
            browser.goForward();
            }          
        });
  }

  /**
   * Setea la funcionalidad de la barra de direcciones
   */
  private void setUrlEditText() {
    urlEditText.setOnKeyListener(new View.OnKeyListener() {
      public boolean onKey(View v, int keyCode, KeyEvent event) {                        
        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
          navigateToUrl();
          return true;
        }
        return false;
      }
      });
    urlEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        public void onFocusChange(View v, boolean hasFocus) {
          Log.d("AdkinBrowser", "onFocusChange " + hasFocus);
          // Select all when focus gained.
          if (hasFocus) {
            urlEditText.setSelection(0, urlEditText.getText().length());
          }
        }
      });
    mUrlTextWatcher = new TextWatcher() {      
        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

        public void afterTextChanged(Editable arg0) {
          updateUI();
        }
      };
    urlEditText.addTextChangedListener(mUrlTextWatcher);
  }
  
  /**
   * Activa la funcionalidad de esconder el teclado cuando se hace click en
   * alguna componente que no sea la barra de input.
   */
  private void setClearText() {
    clearTextListener = new OnTouchListener() {
      public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() != MotionEvent.ACTION_UP){
          return false;
        }
        if(topBarJustShown){
          topBarJustShown = false;
          return false;
        }
        urlEditText.clearFocus();
        hideKeyboard(v);
        hideTopBar();
        hideNavigationButtons();
        browser.requestFocus(View.FOCUS_UP);
        return false;
      }
    };
    browser.setOnTouchListener(clearTextListener);
    //stopBtn.setOnTouchListener(clearTextListener);
    //goBtn.setOnTouchListener(clearTextListener);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.preferences_menu, menu);
    showTopBar();
    showNavigationButtons();
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.preferences:
      startActivity(new Intent(this, PreferencesActivity.class));
      return true;
    case R.id.mail:
      Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data = Uri.parse("mailto:?to=" + "adkmobile@niclabs.cl" );
        intent.setData(data);
        startActivity(intent);
        return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }

  /**
   * Despliega la barra superior del navegador.
   */
  public void showTopBar() {
    if(topBar.getVisibility() == View.VISIBLE)
      return;
    topBar.setVisibility(View.VISIBLE);
    DropDownAnim animation = new DropDownAnim(topBar, topBarHeight, true);
    animation.setDuration(500);
        topBar.startAnimation(animation);
  }
  
  /**
   * Despliega los botones de back y forward.
   */
  public void showNavigationButtons() {
    showBackButton();
    showForwardButton();
  }

  /**
   * Despliega el boton back.
   */
  private void showBackButton() {
    if(backBtn.getVisibility() == View.VISIBLE)
      return;
    if(browser.canGoBack()) {
      backBtn.setVisibility(View.VISIBLE);
      }
    DropDownAnim animation1 = new DropDownAnim(backBtn, navButtonHeight, true);
    animation1.setDuration(500);
    backBtn.startAnimation(animation1);
  }

  /**
   * Despliega el boton forward.
   */
  private void showForwardButton() {
    if(forwardBtn.getVisibility() == View.VISIBLE)
      return;
    if(browser.canGoForward()) {
      forwardBtn.setVisibility(View.VISIBLE);
      }
    DropDownAnim animation2 = new DropDownAnim(forwardBtn, navButtonHeight, true);
    animation2.setDuration(500);    
    forwardBtn.startAnimation(animation2);
  }
  
  /**
   * Oculta la barra superior del navegador.
   */
  public void hideTopBar() {
    if(topBar.getVisibility() == View.GONE)
      return;
    DropDownAnim animation = new DropDownAnim(topBar, topBarHeight, false);
    animation.setDuration(500);
        topBar.startAnimation(animation);
  }
  
  /**
   * Oculta los botones de back y forward.
   */
  public void hideNavigationButtons() {
    hideBackButton();
    hideForwardButton();
  }

  /**
   * Hides the back button
   */
  private void hideBackButton() {
    if(backBtn.getVisibility() == View.GONE)
      return;
    DropDownAnim animation1 = new DropDownAnim(backBtn, navButtonHeight, false);    
    animation1.setDuration(500);    
    backBtn.startAnimation(animation1);
  }
  
  /**
   * Hides the forward button
   */
  private void hideForwardButton() {
    if(forwardBtn.getVisibility() == View.GONE)
      return;
    DropDownAnim animation2 = new DropDownAnim(forwardBtn, navButtonHeight, false);
    animation2.setDuration(500);
    forwardBtn.startAnimation(animation2);
  }
  
  /**
   * Despliega la barra superior del navegador.
   */
  public void showProgressBar() {
    progressBar.setProgress(0);
    progressBar.setVisibility(ProgressBar.VISIBLE);
  }

  /**
   * Oculta la barra progreso del navegador.
   */
  public void hideProgressBar() {
    progressBar.setVisibility(ProgressBar.GONE);
  }

  /**
   * Actualiza la URL de la barra superior del navegador.
   * 
   * @param url
   *            Nueva URL a desplegar en la barra superior
   */
  public void setUrl(String url) {
    if(url.equals(C.defaultStartPageUrl))
      urlEditText.setText(C.defaultStartPage);
    else
      urlEditText.setText(url);
    prevUrl = url;
  }
  
  /**
   * Implementa funcionalidad del Back Button
   */
  @Override
  public boolean onKeyUp(int keyCode, KeyEvent event)  {
      if (keyCode == KeyEvent.KEYCODE_BACK){
        if(browser.canGoBack()) {
          webViewClient.setLoading(false);
        webViewClient.setReloadPending(false);
        browser.stopLoading();
            browser.goBack();
            return true;
        }else{
          this.moveTaskToBack(true);
          return true;
        }
      }
      if(keyCode == KeyEvent.KEYCODE_MENU){
        if(topBar.getVisibility() ==  View.GONE){
          showTopBar();
          showNavigationButtons();
          return false;
        }
      }
      return super.onKeyUp(keyCode, event);
  }
  
  @Override
  public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_BACK:
      this.moveTaskToBack(true);
      return true;
    default: return super.onKeyLongPress(keyCode, event);
    }
  }
  
  /**
     * Navega a la url entregada.
     * @param url La url.
     */
    public void navigateToUrl(String url) {
      Log.d("AdkinBrowser", "navigateToUrl: "+ url);
      if ((url != null) &&
          (url.length() > 0)) {
      
        if (UrlUtils.isUrl(url)) {
          url = UrlUtils.checkUrl(url);
        } else {
          url = UrlUtils.getSearchUrl(this, url);
        }   

        if (url.equals(C.URL_ABOUT_START)) {
          String html = "";
          try {
                InputStream input = getResources().openRawResource(R.raw.page);
                byte[] b = new byte[input.available()];
                input.read(b);
                html = new String(b);
            } catch (IOException e) {
                e.printStackTrace();
            }
          browser.loadDataWithBaseURL(C.defaultStartPageUrl,
               html,
               "text/html", "UTF-8", C.URL_ABOUT_START);
          
        } else {
          prevUrl = url;
          browser.loadUrl(url);          
        }
        //setUrl(url);        
      }
    }        
    
    /**
     * Navega a la url que se encuentre en la barra de direcciones.
     */
    private void navigateToUrl() {
      navigateToUrl(urlEditText.getText().toString());
    }

    /**
     * Maneja los requests provenientes de apps externas.
     * @param intent El intent recibido.
     */
    @Override
  protected void onNewIntent(Intent intent) {
      Log.d("AdkinBrowser", "New intent: " + intent.getDataString());
      if (intent.getData() != null) {
        navigateToUrl(intent.getDataString());
      }
    
    setIntent(intent);
    
    super.onNewIntent(intent);
  }   
    
    /**
     * Esconde el teclado.
     * @param v La vista desde la que se llama la funcin
     */
    private void hideKeyboard(View v) {
      Log.d("AdkinBrowser", "hideKeyboard focused: "+ urlEditText.isFocused());
      if (!urlEditText.isFocused()) {
      InputMethodManager imm = (InputMethodManager) v
          .getContext().getSystemService(
              Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
      hideTopBar();
      hideNavigationButtons();
    }
    }
    
    /**
   * Actualiza la imagen del botn Go.
   */
  public void updateGoButton(){
    if (webViewClient.isLoading()) {
      goBtn.setImageResource(R.drawable.ic_btn_stop);
      //mUrlEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, mCircularProgress, null);
      //((AnimationDrawable) mCircularProgress).start();
    } else {
      if (prevUrl.equals(urlEditText.getText().toString()) && browser.getUrl() != null ){
        goBtn.setImageResource(R.drawable.ic_btn_reload);        
      } else {
        goBtn.setImageResource(R.drawable.ic_btn_go);
      }      
      //((AnimationDrawable) mCircularProgress).stop();
    }
  }
  
  /**
   * Actualiza la UI.
   */
  public void updateUI(){
    Log.d("UI", "webViewClient.isLoading(): " + webViewClient.isLoading());
    updateGoButton();
    updateBackButton();
    updateForwardButton();
  }
    
  private void updateBackButton() {
    if(browser.canGoBack()) {
      showBackButton();
      }else{
        hideBackButton();
      }
  }
  
    private void updateForwardButton() {
      if(browser.canGoForward()) {
      showForwardButton();
      }else{
        hideForwardButton();
      }
  }

  @Override
  protected void onPause() {
    super.onPause();
  }
  
  @Override
  protected void onResume() {
    super.onResume();
  }
  
  @Override
  protected void onSaveInstanceState(Bundle outState) {
    Log.d("AdkinBrowser", "onSaveInstanceState");
    browser.saveState(outState);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
  }

}




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