Android Open Source - retrowatch Retro Web View






From Project

Back to project page retrowatch.

License

The source code is released under:

Apache License

If you think the Android project retrowatch 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 (C) 2014 The Retro Watch - Open source smart watch project
 *// w  w w  .j a v  a 2  s .  c  om
 * 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 com.hardcopy.retrowatch;

import java.net.URISyntaxException;

import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class RetroWebView {
  // Global variables
  private static final String TAG = "RetroWebView";
  
  public static final String URLPrefix = "http://";
  
  // Context, System
  private Context mContext = null;
  private IWebViewListener mWebViewListener = null;
  private InputMethodManager mIMM = null;

  // Layout
  private WebView mWebView = null;
  private ProgressBar mProgressLoading = null;
  private EditText mEditURL = null;
  
  private String mMsgWait = null;

  // WebView components
  private WebSettings mWebViewSettings = null;
  private RetroWebViewClient mWebViewClient = null;
  private RetroChromeClient mChromeClient = null;
  
  
  /*****************************************************
   *    Initializing methods
   ******************************************************/
  public void setParametersForInit(WebView webview, ProgressBar p, EditText e){
    mWebView = webview;
    mProgressLoading = p;
    mEditURL = e;
  }
  
  public void clearHistory() {
    mWebView.clearHistory();
  }
  
  public void initialize(Context c, IWebViewListener l) {
    mContext = c;
    mWebViewListener = l;
    mIMM = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    
    //-----------------------------------------------------------------------------
    // Initialize layout
    //-----------------------------------------------------------------------------
    mEditURL.setOnEditorActionListener(new TextView.OnEditorActionListener() {
      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_GO) {
          actionLoadURL(null);
          // InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure 
          // you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu)
          mIMM.hideSoftInputFromWindow(mEditURL.getWindowToken(), 0);
        }
        return true;
      }
    });

    mMsgWait = mContext.getString(R.string.warning_loading_wait);
        
    //-----------------------------------------------------------------------------
    // Create Web-View and set clients
    //-----------------------------------------------------------------------------
    mWebViewClient = new RetroWebViewClient();
    mChromeClient = new RetroChromeClient();
    mWebView.setWebViewClient(mWebViewClient);
    mWebView.setWebChromeClient(mChromeClient);
    
    
    // Set Web-View features
    mWebViewSettings = mWebView.getSettings();
    mWebViewSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new AndroidBridge(), "hotclip");  // param 2 : JavaScript use this parameter
                                      // ex) javascript call: function getResult() { window.hotclip.setResult('ERROR'); }

    mWebViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    mWebViewSettings.setBuiltInZoomControls(true);
    mWebViewSettings.setLoadWithOverviewMode(true);
    mWebViewSettings.setUseWideViewPort(true);
    //mWebViewSettings.setDatabaseEnabled(true);
    mWebViewSettings.setDomStorageEnabled(true);

    // Set cache size to 8 mb by default. should be more than enough
//    mWebViewSettings.setAppCacheMaxSize(1024*1024*8);
     
    // Enable HTML5 Application Cache
//    String appCachePath = mContext.getCacheDir().getAbsolutePath();
//    mWebViewSettings.setAppCachePath(appCachePath);
//    mWebViewSettings.setAllowFileAccess(true);
//    mWebViewSettings.setAppCacheEnabled(true);
//    mWebViewSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    
//    GeoClient geo = new GeoClient();
//    webview.setWebChromeClient(geo);
//    mWebViewSettings.setGeolocationEnabled(true);
//    mWebViewSettings.setGeolocationDatabasePath(<path>);
    
  }  // End of initialize()
  
  public void finalize() {
    //clearApplicationCache(null);      // Clear all cache files
  } 
  
  
  /*****************************************************
   *    Public methods
   ******************************************************/
  public void actionLoadURL(String inputURL) 
  {
    String url;
    if(inputURL == null || inputURL.length() < 1 || inputURL.equalsIgnoreCase(URLPrefix)) {
      url = mEditURL.getText().toString().trim();
    } else {
      inputURL = inputURL.trim();
      url = inputURL;
    }
    
    if(!url.contains(URLPrefix)) {
      url = URLPrefix + url;
    }

    try {
      mWebView.loadUrl(url);
      // if you want to set HTML code directly
      // mWebView.loadData("<html><body>Hello, world!</body></html>", "text/html", "UTF-8");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public void actionBack() {
    if(mWebView.canGoBack()) {
      mWebView.goBack();
    } else {
      
    }
  }
  
  public WebView getWebViewInstance() {
    return mWebView;
  }
  
  /*****************************************************
   *    Private methods
   ******************************************************/
  private void updateEditText(String str) {
    mEditURL.setText(str);
    mIMM.hideSoftInputFromWindow(mEditURL.getWindowToken(), 0);
  }
  
  // postdata : "param1=value1&param2=value2..."
  private void actionLoadWithPost(String url, String postData) {
    mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
  }
  
  private void startLoading() {
    // Set progress bar
    mProgressLoading.setVisibility(View.VISIBLE);
    mProgressLoading.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 15));
    
    updateEditText(mMsgWait);          // Set loading message in URL box
  }
  
  private void setOnLoading(int progress) {
    mProgressLoading.setProgress(progress);
  }
  
  private void endLoading() {
    mProgressLoading.setVisibility(View.INVISIBLE);
    mProgressLoading.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
  }
  
  // Delete all cache files
  private void clearApplicationCache(java.io.File dir){
    if(dir==null)
      dir = mContext.getCacheDir();
    
    if(dir==null)
        return;

    java.io.File[] children = dir.listFiles();
    try{
      for(int i=0;i<children.length;i++) {
        if(children[i].isDirectory())
          clearApplicationCache(children[i]);
        else children[i].delete();
      }
    }
    catch(Exception e){}
    }
  
  
  /*****************************************************
   *    Etc
   ******************************************************/
  
  
  /*****************************************************
   *    Sub classes
   ******************************************************/
  class RetroChromeClient extends WebChromeClient {
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
      // Page loading progress
      if(newProgress < 100) {
        setOnLoading(newProgress);
      } else {
        // If you want to call JS function while loading, use below code 
        // When page loading finished, call JS function like javascript:[method]
        //view.loadUrl("javascript:getResult");
        endLoading();
      }
    }
    
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
      Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
      result.confirm();
      return true;
    }
  }  // End of class HPChromeClient
 
  
  class RetroWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
      
      startLoading();        // Set loading screen or tasks

      //---------------------------------------------------------------------------------------------------
      // Connect RTSP, Call number and Email link to local application
      //---------------------------------------------------------------------------------------------------
      String origin_url = url;
      String temp_url = origin_url.substring(origin_url.length() - 3, origin_url.length());

      if (temp_url.endsWith("mp4")) {
        // Handle media file
        try {
          Intent i = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
          mContext.startActivity(i);
        } catch (URISyntaxException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        
      } else if (origin_url.startsWith("tel:")) {
        // Call link
        Intent call_phone = new Intent(Intent.ACTION_VIEW, Uri.parse(origin_url));
        // Recursively call current activity with URL
        mContext.startActivity(call_phone);
        return true;
        
      } else if (origin_url.startsWith("mailto:")) {
        // Email link
        String email = origin_url.replace("mailto:", "");
        final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("plain/text");
        intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { email });
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Title");
        intent.putExtra(android.content.Intent.EXTRA_TEXT, "Message");
        mContext.startActivity(Intent.createChooser(intent, "Send email"));

      } else {
        view.loadUrl(url);
      }

      return true;
    }  // End of shouldOverrideUrlLoading()
 
    @Override
    public void onPageFinished(WebView view, String url) {
      // RetroWebView.this.setTitle(view.getTitle());      // Get current page's title
      updateEditText(url);
      
      super.onPageFinished(view, url);
    }
  }  // End of class HPWebViewClient
  
  
  /*******************************************
   * Below methods will be connected with Javascript function
   *******************************************/  
  public class AndroidBridge 
  {
    private final Handler mBridgeHandler = new Handler();      // Android bridge needs a Handler 
    
    // After Android 4.2(JellyBean MR1) release, 
    // interface method must use @JavascriptInterface prefix
    
    @JavascriptInterface
    public void addNewFeed(final String title, final String desc, final String url)  {  // parameters must be final 
      //----- Runnable instance.
      JSRunnable r = new JSRunnable(null, IWebViewListener.WEBVIEW_CALLBACK_ADD_FEED, 0, title, desc, url, null);
      
      //----- Send runnable to handler
      mBridgeHandler.post(r);
    }
  }
  
  private class JSRunnable implements Runnable {
    private String ID = null;
    private int TYPE = 0;
    private int ARG0 = 0;
    private String ARG1 = null;
    private String ARG2 = null;
    private String ARG3 = null;
    private String ARG4 = null;
    
    @Override
    public void run() {
      mWebViewListener.OnReceiveCallback(ID, TYPE,
          ARG0,
          ARG1,    // Title 
          ARG2,     // Desc
          ARG3,     // URL
          ARG4);
    }
    
    public JSRunnable(String id, int type, int arg0, String arg1, String arg2, String arg3, String arg4) {
      ID = id;
      TYPE = type;
      ARG0 = arg0; 
      ARG1 = arg1;
      ARG2 = arg2;
      ARG3 = arg3;
      ARG4 = arg4;
    }
  }
}




Java Source Code List

com.hardcopy.retrowatch.DeviceListActivity.java
com.hardcopy.retrowatch.FiltersAdapter.java
com.hardcopy.retrowatch.FiltersFragment.java
com.hardcopy.retrowatch.IAdapterListener.java
com.hardcopy.retrowatch.IDialogListener.java
com.hardcopy.retrowatch.IFragmentListener.java
com.hardcopy.retrowatch.IWebViewListener.java
com.hardcopy.retrowatch.MessageListAdapter.java
com.hardcopy.retrowatch.MessageListDialog.java
com.hardcopy.retrowatch.MessageListFragment.java
com.hardcopy.retrowatch.RetroWatchActivity.java
com.hardcopy.retrowatch.RetroWatchFragmentAdapter.java
com.hardcopy.retrowatch.RetroWebViewActivity.java
com.hardcopy.retrowatch.RetroWebView.java
com.hardcopy.retrowatch.RssAdapter.java
com.hardcopy.retrowatch.RssFragment.java
com.hardcopy.retrowatch.WatchControlFragment.java
com.hardcopy.retrowatch.connectivity.BluetoothManager.java
com.hardcopy.retrowatch.connectivity.ConnectionInfo.java
com.hardcopy.retrowatch.connectivity.HttpAsyncTask.java
com.hardcopy.retrowatch.connectivity.HttpFileAsyncTask.java
com.hardcopy.retrowatch.connectivity.HttpInterface.java
com.hardcopy.retrowatch.connectivity.HttpListener.java
com.hardcopy.retrowatch.connectivity.HttpRequester.java
com.hardcopy.retrowatch.connectivity.TransactionBuilder.java
com.hardcopy.retrowatch.connectivity.TransactionReceiver.java
com.hardcopy.retrowatch.contents.ContentManager.java
com.hardcopy.retrowatch.contents.FeedManager.java
com.hardcopy.retrowatch.contents.FeedParser.java
com.hardcopy.retrowatch.contents.GmailContract.java
com.hardcopy.retrowatch.contents.IContentManagerListener.java
com.hardcopy.retrowatch.contents.IFeedListener.java
com.hardcopy.retrowatch.contents.objects.CPObject.java
com.hardcopy.retrowatch.contents.objects.ContentObject.java
com.hardcopy.retrowatch.contents.objects.EmergencyObject.java
com.hardcopy.retrowatch.contents.objects.FeedObject.java
com.hardcopy.retrowatch.contents.objects.FilterObject.java
com.hardcopy.retrowatch.contents.objects.MessagingObject.java
com.hardcopy.retrowatch.contents.objects.NotificationObject.java
com.hardcopy.retrowatch.database.DBHelper.java
com.hardcopy.retrowatch.service.NotificationReceiverService.java
com.hardcopy.retrowatch.service.RetroWatchService.java
com.hardcopy.retrowatch.service.ServiceMonitoring.java
com.hardcopy.retrowatch.utils.Constants.java
com.hardcopy.retrowatch.utils.Logs.java
com.hardcopy.retrowatch.utils.RecycleUtils.java
com.hardcopy.retrowatch.utils.Settings.java
com.hardcopy.retrowatch.utils.Utils.java
com.hardcopy.retrowatchle.DeviceListActivity.java
com.hardcopy.retrowatchle.FiltersAdapter.java
com.hardcopy.retrowatchle.FiltersFragment.java
com.hardcopy.retrowatchle.IAdapterListener.java
com.hardcopy.retrowatchle.IDialogListener.java
com.hardcopy.retrowatchle.IFragmentListener.java
com.hardcopy.retrowatchle.IWebViewListener.java
com.hardcopy.retrowatchle.MessageListAdapter.java
com.hardcopy.retrowatchle.MessageListDialog.java
com.hardcopy.retrowatchle.MessageListFragment.java
com.hardcopy.retrowatchle.RetroWatchActivity.java
com.hardcopy.retrowatchle.RetroWatchFragmentAdapter.java
com.hardcopy.retrowatchle.RetroWebViewActivity.java
com.hardcopy.retrowatchle.RetroWebView.java
com.hardcopy.retrowatchle.RssAdapter.java
com.hardcopy.retrowatchle.RssFragment.java
com.hardcopy.retrowatchle.WatchControlFragment.java
com.hardcopy.retrowatchle.connectivity.BluetoothManager.java
com.hardcopy.retrowatchle.connectivity.ConnectionInfo.java
com.hardcopy.retrowatchle.connectivity.HttpAsyncTask.java
com.hardcopy.retrowatchle.connectivity.HttpFileAsyncTask.java
com.hardcopy.retrowatchle.connectivity.HttpInterface.java
com.hardcopy.retrowatchle.connectivity.HttpListener.java
com.hardcopy.retrowatchle.connectivity.HttpRequester.java
com.hardcopy.retrowatchle.connectivity.TransactionBuilder.java
com.hardcopy.retrowatchle.connectivity.TransactionReceiver.java
com.hardcopy.retrowatchle.contents.ContentManager.java
com.hardcopy.retrowatchle.contents.FeedManager.java
com.hardcopy.retrowatchle.contents.FeedParser.java
com.hardcopy.retrowatchle.contents.GmailContract.java
com.hardcopy.retrowatchle.contents.IContentManagerListener.java
com.hardcopy.retrowatchle.contents.IFeedListener.java
com.hardcopy.retrowatchle.contents.objects.CPObject.java
com.hardcopy.retrowatchle.contents.objects.ContentObject.java
com.hardcopy.retrowatchle.contents.objects.EmergencyObject.java
com.hardcopy.retrowatchle.contents.objects.FeedObject.java
com.hardcopy.retrowatchle.contents.objects.FilterObject.java
com.hardcopy.retrowatchle.contents.objects.MessagingObject.java
com.hardcopy.retrowatchle.contents.objects.NotificationObject.java
com.hardcopy.retrowatchle.database.DBHelper.java
com.hardcopy.retrowatchle.service.RetroWatchService.java
com.hardcopy.retrowatchle.service.ServiceMonitoring.java
com.hardcopy.retrowatchle.utils.Constants.java
com.hardcopy.retrowatchle.utils.Logs.java
com.hardcopy.retrowatchle.utils.RecycleUtils.java
com.hardcopy.retrowatchle.utils.Settings.java
com.hardcopy.retrowatchle.utils.Utils.java