Example usage for android.webkit WebView setWebContentsDebuggingEnabled

List of usage examples for android.webkit WebView setWebContentsDebuggingEnabled

Introduction

In this page you can find the example usage for android.webkit WebView setWebContentsDebuggingEnabled.

Prototype

public static void setWebContentsDebuggingEnabled(boolean enabled) 

Source Link

Document

Enables debugging of web contents (HTML / CSS / JavaScript) loaded into any WebViews of this application.

Usage

From source file:com.wipro.sa349342.wmar.AbstractArchitectCamActivity.java

/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override/*from   ww  w.  j a v  a2  s  .com*/
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /* pressing volume up/down should cause music volume changes */
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

    /* set samples content view */
    this.setContentView(this.getContentViewId());

    this.setTitle(this.getActivityTitle());

    View mapFrag = findViewById(R.id.map);

    if (this.isMapPanelRequired()) {

        mapFrag.setVisibility(View.VISIBLE);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(map);

        mapFragment.getMapAsync(AbstractArchitectCamActivity.this);
    } else {
        mapFrag.setVisibility(View.GONE);
    }

    /*
     *   this enables remote debugging of a WebView on Android 4.4+ when debugging = true in AndroidManifest.xml
     *   If you get a compile time error here, ensure to have SDK 19+ used in your ADT/Eclipse.
     *   You may even delete this block in case you don't need remote debugging or don't have an Android 4.4+ device in place.
     *   Details: https://developers.google.com/chrome-developer-tools/docs/remote-debugging
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
    }

    /* set AR-view for life-cycle notifications etc. */

    this.architectView = (ArchitectView) this.findViewById(this.getArchitectViewId());

    /* pass SDK key if you have one, this one is only valid for this package identifier and must not be used somewhere else */
    final StartupConfiguration config = new StartupConfiguration(this.getWikitudeSDKLicenseKey(),
            this.getFeatures(), this.getCameraPosition());

    try {
        /* first mandatory life-cycle notification */
        this.architectView.onCreate(config);
    } catch (RuntimeException rex) {
        this.architectView = null;
        Toast.makeText(getApplicationContext(), "can't create Architect View", Toast.LENGTH_SHORT).show();
        Log.e(this.getClass().getName(), "Exception in ArchitectView.onCreate()", rex);
    }

    // set accuracy listener if implemented, you may e.g. show calibration prompt for compass using this listener
    this.sensorAccuracyListener = this.getSensorAccuracyListener();

    // set urlListener, any calls made in JS like "document.location = 'architectsdk://foo?bar=123'" is forwarded to this listener, use this to interact between JS and native Android activity/fragment
    this.urlListener = this.getUrlListener();

    // register valid urlListener in architectView, ensure this is set before content is loaded to not miss any event
    if (this.urlListener != null && this.architectView != null) {
        this.architectView.registerUrlListener(this.getUrlListener());
    }

    if (hasGeo()) {
        // listener passed over to locationProvider, any location update is handled here
        this.locationListener = new LocationListener() {

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
            }

            @Override
            public void onProviderEnabled(String provider) {
            }

            @Override
            public void onProviderDisabled(String provider) {
            }

            @Override
            public void onLocationChanged(final Location location) {
                // forward location updates fired by LocationProvider to architectView, you can set lat/lon from any location-strategy
                if (location != null) {
                    // sore last location as member, in case it is needed somewhere (in e.g. your adjusted project)
                    AbstractArchitectCamActivity.this.lastKnownLocaton = location;
                    if (AbstractArchitectCamActivity.this.architectView != null) {
                        // check if location has altitude at certain accuracy level & call right architect method (the one with altitude information)
                        if (location.hasAltitude() && location.hasAccuracy() && location.getAccuracy() < 7) {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(), location.getAltitude(), location.getAccuracy());
                        } else {
                            AbstractArchitectCamActivity.this.architectView.setLocation(location.getLatitude(),
                                    location.getLongitude(),
                                    location.hasAccuracy() ? location.getAccuracy() : 1000);
                        }
                    }

                    // currentLocationMarker(location);
                }
            }
        };

        // locationProvider used to fetch user position
        this.locationProvider = getLocationProvider(this.locationListener);

    } else {
        this.locationProvider = null;
        this.locationListener = null;
    }
}

From source file:com.mb.android.MainActivity.java

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

    Current = this;

    /*new Runnable() {/* w  ww . j a  v a  2 s .c om*/
    @Override
    public void run() {
        readLogcatInBackground();
    }
    }.run();*/

    /*try {
    // This is throwing an exception we can't catch and is crashing the app
     URL.setURLStreamHandlerFactory(new OkUrlFactory(okHttpClient));
    }
    catch (Exception ex){
    // Occasionally seeing factory already set error
    }*/

    // Set by <content src="index.html" /> in config.xml
    loadUrl(launchUrl);

    /* Prepare the progressBar */
    IntentFilter filter = new IntentFilter();
    filter.addAction(Constants.ACTION_SHOW_PLAYER);
    registerReceiver(messageReceiver, filter);

    if (enableSystemWebView()) {

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                // This is causing a crash on some devices
                WebView.setWebContentsDebuggingEnabled(true);
            }
        } catch (Exception ex) {
            // This is causing a crash on some devices
            getLogger().ErrorException("Error enabling webview debugging", ex);
        }
        addJavascriptInterfaces();
    }
}

From source file:edu.tjhsst.ion.gcmFrame.MainActivity.java

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

    this.setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.navbar_color));

    }//  www  .  java  2 s.c om
    // requestWindowFeature(Window.FEATURE_NO_TITLE);

    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
            if (sentToken) {
                Log.i(TAG, "Google token sent");

            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.token_error_message),
                        Toast.LENGTH_LONG).show();
            }
        }

    };

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        startService(intent);
    }

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) {
        NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
        if (ni != null) {
            NetworkInfo.State state = ni.getState();
            if (state == null || state != NetworkInfo.State.CONNECTED) {
                // record the fact that there is no connection
                isConnected = false;
            }
        }
    }

    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.ION_SETUP, false);

    webView = (WebView) findViewById(R.id.webview);

    webView.setInitialScale(1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setLoadWithOverviewMode(true);

    webView.getSettings().setUseWideViewPort(true);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    webView.setScrollbarFadingEnabled(false);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    StringBuilder uaString = new StringBuilder(webView.getSettings().getUserAgentString());
    uaString.append(" - IonAndroid: gcmFrame (");
    if (sentToken) {
        uaString.append("appRegistered:True");
    } else {
        uaString.append("appRegistered:False");
    }
    uaString.append(" osVersion:").append(System.getProperty("os.version"));
    uaString.append(" apiLevel:").append(android.os.Build.VERSION.SDK_INT);
    uaString.append(" Device:").append(android.os.Build.DEVICE);
    uaString.append(" Model:").append(android.os.Build.MODEL);
    uaString.append(" Product:").append(android.os.Build.PRODUCT);
    uaString.append(")");
    webView.getSettings().setUserAgentString(uaString.toString());

    webView.setNetworkAvailable(isConnected);

    webView.addJavascriptInterface(new WebAppInterface(this), "IonAndroidInterface");

    webView.loadUrl(MainActivity.ION_HOST);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, "Loading " + url);
            if (!isConnected) {
                String html = getHtml("offline.html");
                html = html.replaceAll("\\[url\\]", url);
                view.loadData(html, "text/html", "utf-8");
                return true;
            } else if (url.contains(ION_HOST)) {
                // keep in WebView
                webView.loadUrl(url);
                return true;
            } else {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
                return true;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // if (errorCode == ERROR_TIMEOUT)
            view.stopLoading(); // may not be needed
            String html = getHtml("timeout.html");
            html = html.replaceAll("\\[url\\]", failingUrl);
            html = html.replaceAll("\\[desc\\]", description);
            view.loadData(html, "text/html", "utf-8");
        }
    });

}

From source file:org.runbuddy.libtomahawk.resolver.ScriptAccount.java

@SuppressLint({ "AddJavascriptInterface", "SetJavaScriptEnabled" })
public ScriptAccount(String path, boolean manuallyInstalled) {
    String prefix = manuallyInstalled ? "file://" : "file:///android_asset";
    mPath = prefix + path;/*w ww. j a  v  a 2  s . c  o  m*/
    mManuallyInstalled = manuallyInstalled;
    String[] parts = mPath.split("/");
    mName = parts[parts.length - 1];
    InputStream inputStream = null;
    try {
        if (mManuallyInstalled) {
            File metadataFile = new File(path + File.separator + "content" + File.separator + "metadata.json");
            inputStream = new FileInputStream(metadataFile);
        } else {
            inputStream = TomahawkApp.getContext().getAssets()
                    .open(path.substring(1) + "/content/metadata.json");
        }
        String metadataString = IOUtils.toString(inputStream, Charsets.UTF_8);
        mMetaData = GsonHelper.get().fromJson(metadataString, ScriptResolverMetaData.class);
        if (mMetaData == null) {
            Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount.");
            return;
        }
    } catch (IOException e) {
        Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage());
        Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount.");
        return;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
        }
    }

    CookieManager.setAcceptFileSchemeCookies(true);

    mWebView = new WebView(TomahawkApp.getContext());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
    }
    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        //noinspection deprecation
        settings.setDatabasePath(TomahawkApp.getContext().getDir("databases", Context.MODE_PRIVATE).getPath());
    }
    settings.setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new TomahawkWebChromeClient());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //initalize WebView
            String data = "<!DOCTYPE html>" + "<html>" + "<head><title>" + mName + "</title></head>" + "<body>"
                    + "<script src=\"file:///android_asset/js/rsvp-latest.min.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/cryptojs-core.js"
                    + "\" type=\"text/javascript\"></script>";
            if (mMetaData.manifest.scripts != null) {
                for (String scriptPath : mMetaData.manifest.scripts) {
                    data += "<script src=\"" + mPath + "/content/" + scriptPath
                            + "\" type=\"text/javascript\"></script>";
                }
            }
            try {
                String[] cryptoJsScripts = TomahawkApp.getContext().getAssets().list("js/cryptojs");
                for (String scriptPath : cryptoJsScripts) {
                    data += "<script src=\"file:///android_asset/js/cryptojs/" + scriptPath
                            + "\" type=\"text/javascript\"></script>";
                }
            } catch (IOException e) {
                Log.e(TAG, "ScriptResolver: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
            data += "<script src=\"file:///android_asset/js/tomahawk_android_pre.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk-infosystem.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk_android_post.js"
                    + "\" type=\"text/javascript\"></script>" + "<script src=\"" + mPath + "/content/"
                    + mMetaData.manifest.main + "\" type=\"text/javascript\"></script>" + "</body></html>";
            mWebView.setWebViewClient(new ScriptWebViewClient(ScriptAccount.this));
            mWebView.addJavascriptInterface(new ScriptInterface(ScriptAccount.this), SCRIPT_INTERFACE_NAME);
            mWebView.loadDataWithBaseURL("file:///android_asset/test.html", data, "text/html", null, null);
        }
    });
}

From source file:moose.com.ac.ArticleViewActivity.java

@Override
protected void onInitView(Bundle savedInstanceState) {
    setContentView(R.layout.activity_article_view);
    article = (Article) getIntent().getSerializableExtra(Config.ARTICLE);
    /*//from ww w .j  a  va  2s . c  o  m
    * Uri data = getIntent().getData();
    if(Intent.ACTION_VIEW.equalsIgnoreCase(getIntent().getAction()) && data!=null){
    String scheme = data.getScheme();
    if(scheme.equals("ac")){
        // ac://ac000000
        aid = Integer.parseInt(getIntent().getDataString().substring(7));
    }else if(scheme.equals("http")){
        // http://www.acfun.tv/v/ac123456
        Matcher matcher;
        String path = data.getPath();
        if(path==null){
            finish();
            return;
        }
        if((matcher = sVreg.matcher(path)).find()
                || (matcher = sAreg.matcher(path)).find()){
            aid = Integer.parseInt(matcher.group(1));
        }
    }
    if(aid != 0) title = "ac"+aid;
    isWebMode = getIntent().getBooleanExtra("webmode", false) && aid == 0;
    }else{
    aid = getIntent().getIntExtra("aid", 0);
    title = getIntent().getStringExtra("title");
    }*/
    isFav = dbHelper.isExits(TAB_NAME, article.isfav);
    articleId = Integer.valueOf(article.contentId);
    toolbarHeight = DisplayUtil.dip2px(this, 56f);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final ActionBar ab = getSupportActionBar();
    if (ab != null) {
        ab.setDisplayHomeAsUpEnabled(true);
    }
    contend = "ac" + articleId;
    getSupportActionBar().setTitle(contend);

    fab = (FloatingActionButton) findViewById(R.id.view_fab);
    fab.setOnClickListener(v -> {
        Intent intent = new Intent(this, BigNewsActivity.class);
        intent.putExtra(Config.CONTENTID, String.valueOf(articleId));
        intent.putExtra(Config.TITLE, title);
        startActivity(intent);
    });

    mSwipeRefreshLayout = (MultiSwipeRefreshLayout) findViewById(R.id.web_swipe);
    mSwipeRefreshLayout.setSwipeableChildren(R.id.view_fab);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.md_white);
    mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(R.color.colorPrimary);

    mWeb = (ObservableWebView) findViewById(R.id.view_webview);
    mContentView = (CoordinatorLayout) findViewById(R.id.view_content);
    settings = mWeb.getSettings();
    settings.setJavaScriptEnabled(true);
    //settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    settings.setUserAgentString(RxUtils.UA);
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setDefaultTextEncodingName(Config.TEXT_ENCODING);
    settings.setSupportZoom(true);
    settings.setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        mWeb.getSettings().setDisplayZoomControls(false);
    }
    mWeb.setWebViewClient(new Client());
    mWeb.addJavascriptInterface(new JsBridge(), "JsBridge");
    if (Build.VERSION.SDK_INT >= 11)
        mWeb.setBackgroundColor(Color.argb(1, 0, 0, 0));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
    }

    mWeb.setOnScrollChangedCallback(this);
    level = CommonUtil.getTextSize();
    setText();
    mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(true));
    initData();
}

From source file:com.jaspersoft.android.jaspermobile.activities.viewer.html.report.fragment.NodeWebViewFragment.java

@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
private void prepareWebView() {
    // disable hardware acceleration
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }/*from   w ww .j a  v a 2  s.c o m*/
    // configure additional settings
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    webView.setWebViewClient(jsWebViewClient);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setUseWideViewPort(true);

    if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
}

From source file:org.readium.sdk.android.launcher.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    mWebview = (WebView) findViewById(R.id.webview);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && 0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
        WebView.setWebContentsDebuggingEnabled(true);
    }/* w  w w. j  a  va 2 s  .co m*/

    mPageInfo = (TextView) findViewById(R.id.page_info);
    initWebView();

    Intent intent = getIntent();
    if (intent.getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mContainer = ContainerHolder.getInstance().get(extras.getLong(Constants.CONTAINER_ID));
            if (mContainer == null) {
                finish();
                return;
            }
            mPackage = mContainer.getDefaultPackage();

            String rootUrl = "http://" + EpubServer.HTTP_HOST + ":" + EpubServer.HTTP_PORT + "/";
            mPackage.setRootUrls(rootUrl, null);

            try {
                mOpenPageRequestData = OpenPageRequest
                        .fromJSON(extras.getString(Constants.OPEN_PAGE_REQUEST_DATA));
            } catch (JSONException e) {
                Log.e(TAG, "Constants.OPEN_PAGE_REQUEST_DATA must be a valid JSON object: " + e.getMessage(),
                        e);
            }
        }
    }

    // No need, EpubServer already launchers its own thread
    // new AsyncTask<Void, Void, Void>() {
    // @Override
    // protected Void doInBackground(Void... params) {
    // //xxx
    // return null;
    // }
    // }.execute();

    mServer = new EpubServer(EpubServer.HTTP_HOST, EpubServer.HTTP_PORT, mPackage, quiet, dataPreProcessor);
    mServer.startServer();

    // Load the page skeleton
    mWebview.loadUrl(READER_SKELETON);
    mViewerSettings = new ViewerSettings(ViewerSettings.SyntheticSpreadMode.AUTO,
            ViewerSettings.ScrollMode.AUTO, 100, 20);

    mReadiumJSApi = new ReadiumJSApi(new ReadiumJSApi.JSLoader() {
        @Override
        public void loadJS(String javascript) {
            mWebview.loadUrl(javascript);
        }
    });
}

From source file:org.cobaltians.cobalt.fragments.CobaltFragment.java

protected void setWebViewSettings(CobaltFragment javascriptInterface) {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD)
        mWebView.setOverScrollMode(View.OVER_SCROLL_IF_CONTENT_SCROLLS);
    mWebView.setScrollListener(this);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    // Enables JS
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Enables and setups JS local storage
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    //@deprecated since API 19. But calling this method have simply no effect for API 19+
    webSettings.setDatabasePath(mContext.getFilesDir().getParentFile().getPath() + "/databases/");

    // Enables cross-domain calls for Ajax
    allowAjax();/*from w w  w .j a v  a  2  s  . c  om*/

    // Fix some focus issues on old devices like HTC Wildfire
    // keyboard was not properly showed on input touch.
    mWebView.requestFocus(View.FOCUS_DOWN);
    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!view.hasFocus()) {
                    view.requestFocus();
                }
                break;
            default:
                break;
            }

            return false;
        }
    });

    //Enable Webview debugging from chrome desktop
    if (Cobalt.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    // Add JavaScript interface so JavaScript can call native functions.
    mWebView.addJavascriptInterface(javascriptInterface, "Android");
    mWebView.addJavascriptInterface(new LocalStorageJavaScriptInterface(mContext), "LocalStorage");

    WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            executeWaitingCalls();
        }
    };

    mWebView.setWebViewClient(webViewClient);
}

From source file:it.rignanese.leo.slimtwitter.MainActivity.java

private void setUpWebViewDefaults(WebView webView) {
    WebSettings settings = webView.getSettings();

    // Enable Javascript
    settings.setJavaScriptEnabled(true);

    // Use WideViewport and Zoom out if there is no viewport defined
    settings.setUseWideViewPort(true);/*from  ww  w .  j a  va2  s .  com*/
    settings.setLoadWithOverviewMode(true);

    // Enable pinch to zoom without the zoom buttons
    settings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        settings.setDisplayZoomControls(false);
    }

    // Enable remote debugging via chrome://inspect
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
}

From source file:org.readium.sdk.android.biblemesh.WebViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

    setContentView(R.layout.activity_web_view);

    final int abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
    findViewById(abTitleId).setOnClickListener(new View.OnClickListener() {

        @Override/*from  www.  j  a  v  a 2  s. c  o m*/
        public void onClick(View v) {
            finish();
        }
    });

    mWebview = (WebView) findViewById(R.id.webview);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && 0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    mProgress = (ProgressBar) findViewById(R.id.progressBar);
    initWebView();

    final GestureDetector gestureDetector = new GestureDetector(this, new MyGestureListener());

    mWebview.setOnTouchListener(new View.OnTouchListener() {

        private final static long MAX_TOUCH_DURATION = 150;
        float lastEventX;
        float m_DownTime;

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastEventX = event.getX();
                m_DownTime = event.getEventTime(); //init time
                break;
            case MotionEvent.ACTION_MOVE: {
                float distanceX = lastEventX - event.getX();

                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                marginLayoutParams.leftMargin = marginLayoutParams.leftMargin - (int) distanceX;
                marginLayoutParams.rightMargin = -marginLayoutParams.leftMargin;// marginLayoutParams.rightMargin + (int) distanceX;

                mWebview.requestLayout();
            }
                break;
            case MotionEvent.ACTION_UP: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();
                if (marginLayoutParams.leftMargin < 10 && marginLayoutParams.leftMargin > -10) {
                    Log.i("up", "small margin, open menu?");
                    if (event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION) {
                        Log.i("up", "quick");
                        showActionBar(null);
                    } else {
                        Log.i("up", "too long");
                    }
                }
            }
            case MotionEvent.ACTION_CANCEL: {
                ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) mWebview
                        .getLayoutParams();

                //Log.i("snap", "snap width: "+mWebview.getWidth()+" left:" + marginLayoutParams.leftMargin + " raw:" + event.getRawX() + " " + event.getX());//+" "+e2.toString()+" "+e1.toString());
                //mWebview.getWidth()
                if (marginLayoutParams.leftMargin < -0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageRight();
                    mWebview.setAlpha(0.0f);
                } else if (marginLayoutParams.leftMargin > 0.5 * mWebview.getWidth()) {
                    mReadiumJSApi.openPageLeft();
                    mWebview.setAlpha(0.0f);
                } else {
                    snapBack();
                    //return true;
                }
            }
                break;
            }
            ;
            return gestureDetector.onTouchEvent(event);
        }
    });
    /*mWebview.setHapticFeedbackEnabled(false);*/

    Intent intent = getIntent();
    if (intent.getFlags() == Intent.FLAG_ACTIVITY_NEW_TASK) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mContainer = ContainerHolder.getInstance().get(extras.getLong(Constants.CONTAINER_ID));
            if (mContainer == null) {
                finish();
                return;
            }
            mPackage = mContainer.getDefaultPackage();

            String rootUrl = "http://" + EpubServer.HTTP_HOST + ":" + EpubServer.HTTP_PORT + "/";
            mPackage.setRootUrls(rootUrl, null);

            try {
                mOpenPageRequestData = OpenPageRequest
                        .fromJSON(extras.getString(Constants.OPEN_PAGE_REQUEST_DATA));
            } catch (JSONException e) {
                Log.e(TAG, "Constants.OPEN_PAGE_REQUEST_DATA must be a valid JSON object: " + e.getMessage(),
                        e);
            }
        }
    }

    // No need, EpubServer already launchers its own thread
    // new AsyncTask<Void, Void, Void>() {
    // @Override
    // protected Void doInBackground(Void... params) {
    // //xxx
    // return null;
    // }
    // }.execute();

    mServer = new EpubServer(EpubServer.HTTP_HOST, EpubServer.HTTP_PORT, mPackage, quiet, dataPreProcessor);
    mServer.startServer();

    // Load the page skeleton
    mWebview.loadUrl(READER_SKELETON);
    mViewerSettings = new ViewerSettings(ViewerSettings.SyntheticSpreadMode.SINGLE,
            ViewerSettings.ScrollMode.AUTO, 100, 20);

    mReadiumJSApi = new ReadiumJSApi(new ReadiumJSApi.JSLoader() {
        @Override
        public void loadJS(String javascript) {
            mWebview.loadUrl(javascript);
        }
    });

    /*Button back = (Button)findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
    onBackPressed();
    if(getActionBar.isShowing())
    {
       hideActionBar();
    }
    else
    {
       getActionBar.show();
       hideActionBar();
    }
       }
    });*/
    r = new Runnable() {
        @Override
        public void run() {
            getActionBar().hide();
            //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        }
    };
    hide2 = null;
    hideActionBar();
    //ActionBar actionBar = getActionBar();
    //actionBar.hide();
    //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}