Example usage for android.webkit WebView loadDataWithBaseURL

List of usage examples for android.webkit WebView loadDataWithBaseURL

Introduction

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

Prototype

public void loadDataWithBaseURL(@Nullable String baseUrl, String data, @Nullable String mimeType,
        @Nullable String encoding, @Nullable String historyUrl) 

Source Link

Document

Loads the given data into this WebView, using baseUrl as the base URL for the content.

Usage

From source file:org.botlibre.sdk.activity.ChatActivity.java

public void submitCorrection() {
    final EditText text = new EditText(this);
    MainActivity.prompt("Enter correction to the bot's response (what it should have said)", this, text,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (instance == null) {
                        return;
                    }//  w w w .  j a  v a2  s .  com

                    ChatConfig config = new ChatConfig();
                    config.instance = instance.id;
                    config.conversation = MainActivity.conversation;
                    config.speak = !MainActivity.deviceVoice;
                    config.avatar = avatarId;
                    if (MainActivity.disableVideo) {
                        config.avatarFormat = "image";
                    } else {
                        config.avatarFormat = MainActivity.webm ? "webm" : "mp4";
                    }
                    config.avatarHD = MainActivity.hd;

                    config.message = text.getText().toString().trim();
                    if (config.message.equals("")) {
                        return;
                    }
                    messages.add(config);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ListView list = (ListView) findViewById(R.id.chatList);
                            ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                            list.invalidateViews();
                        }

                    });

                    config.correction = true;

                    Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin);
                    config.emote = emoteSpin.getSelectedItem().toString();

                    HttpChatAction action = new HttpChatAction(ChatActivity.this, config);
                    action.execute();

                    EditText v = (EditText) findViewById(R.id.messageText);
                    v.setText("");
                    emoteSpin.setSelection(0);
                    resetToolbar();

                    WebView responseView = (WebView) findViewById(R.id.responseText);
                    responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);

                }
            });
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public void flagResponse() {
    if (MainActivity.user == null) {
        MainActivity.showMessage("You must sign in to flag a response", this);
        return;//from   w w  w.java2 s.c  om
    }
    final EditText text = new EditText(this);
    MainActivity.prompt("Enter reason for flagging response as offensive", this, text,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    if (instance == null) {
                        return;
                    }
                    ChatConfig config = new ChatConfig();
                    config.instance = instance.id;
                    config.conversation = MainActivity.conversation;
                    config.speak = !MainActivity.deviceVoice;
                    config.avatar = avatarId;
                    if (MainActivity.translate && MainActivity.voice != null) {
                        config.language = MainActivity.voice.language;
                    }
                    if (MainActivity.disableVideo) {
                        config.avatarFormat = "image";
                    } else {
                        config.avatarFormat = MainActivity.webm ? "webm" : "mp4";
                    }
                    config.avatarHD = MainActivity.hd;

                    config.message = text.getText().toString().trim();
                    if (config.message.equals("")) {
                        return;
                    }
                    messages.add(config);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ListView list = (ListView) findViewById(R.id.chatList);
                            ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                            list.invalidateViews();
                        }

                    });

                    config.offensive = true;

                    Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin);
                    config.emote = emoteSpin.getSelectedItem().toString();

                    HttpChatAction action = new HttpChatAction(ChatActivity.this, config);
                    action.execute();

                    EditText v = (EditText) findViewById(R.id.messageText);
                    v.setText("");
                    emoteSpin.setSelection(0);
                    resetToolbar();

                    WebView responseView = (WebView) findViewById(R.id.responseText);
                    responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);
                }
            });
}

From source file:it.redturtle.mobile.apparpav.ForecastFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.showbulletin, container, false);

    // Set button in order to start the bulletin fragmnet
    final Button mv = (Button) view.findViewById(R.id.mv);
    mv.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent newintent = new Intent();
            newintent.setClass(activity, BulletinActivity.class);
            newintent.putExtra("bulletinid", "MV");
            startActivity(newintent);/* w  ww .  ja  v a2 s  .  co  m*/
        }
    });

    // Set button in order to start the bulletin fragmnet
    final Button dm = (Button) view.findViewById(R.id.dm);
    dm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent newintent = new Intent();
            newintent.setClass(activity, BulletinActivity.class);
            newintent.putExtra("bulletinid", "DM");
            startActivity(newintent);
        }
    });

    // Set button in order to start the bulletin fragmnet
    final Button pm = (Button) view.findViewById(R.id.pm);
    pm.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent newintent = new Intent();
            newintent.setClass(activity, BulletinActivity.class);
            newintent.putExtra("bulletinid", "MP");
            startActivity(newintent);
        }
    });

    WebView webview = (WebView) view.findViewById(R.id.datail_content);
    webview.setWebChromeClient(new WebChromeClient() {
    });
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setBuiltInZoomControls(true);
    webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    String html = "<!doctype html>";
    html += "<html>";
    html += "<head>";
    html += "<meta name=\"author\" content=\"RedTurtle.it\" />";
    html += "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />";
    html += "</head>";
    html += "<body style=\"font-family:Helvetica;font-size:small;\">";
    html += "<div style=\"text-align:center;\"><b>" + forecast.getName() + "</b></div>";

    if (forecast.getType() == 1) {
        html += "<div style=\"text-align:center;\">";
        html += "<p>" + forecast.getCaptionAt(0) + "</p>";
        html += "<img src=\"" + forecast.getPathAt(0) + "\" width=\"140\" style=\"padding:2px;\"/>";
        html += "</div>";
    }
    if (forecast.getType() == 2) {

        html += "<div style=\"text-align:center;\">";
        html += "<div style=\"display:inline-block;\">";
        html += "<div style=\"float:left;\">";
        html += "<p>" + forecast.getCaptionAt(0) + "</p>";
        html += "<img src=\"" + forecast.getPathAt(0) + "\" width=\"140\" style=\"padding:2px;\"/>";
        html += "</div>";
        html += "<div style=\"float:left;\">";
        html += "<p>" + forecast.getCaptionAt(1) + "</p>";
        html += "<img  src=\"" + forecast.getPathAt(1) + "\" width=\"140\" style=\"padding:2px;\"/>";
        html += "</div>";
        html += "</div>";
        html += "</div>";
    }

    html += forecast.getBody();
    html += "</body>";
    html += "</html>";

    webview.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
    return view;
}

From source file:com.androzic.waypoint.WaypointInfo.java

@SuppressLint("NewApi")
private void updateWaypointInfo(double lat, double lon) {
    Androzic application = Androzic.getApplication();
    Activity activity = getActivity();//from   w  ww .j  a  v  a 2s  . co  m
    Dialog dialog = getDialog();
    View view = getView();

    WebView description = (WebView) view.findViewById(R.id.description);

    if ("".equals(waypoint.description)) {
        description.setVisibility(View.GONE);
    } else {
        String descriptionHtml;
        try {
            TypedValue tv = new TypedValue();
            Theme theme = activity.getTheme();
            Resources resources = getResources();
            theme.resolveAttribute(android.R.attr.textColorSecondary, tv, true);
            int secondaryColor = resources.getColor(tv.resourceId);
            String css = String.format(
                    "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n",
                    (secondaryColor & 0x00FFFFFF));
            descriptionHtml = css + waypoint.description;
            description.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    view.setBackgroundColor(Color.TRANSPARENT);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
                }
            });
            description.setBackgroundColor(Color.TRANSPARENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        } catch (Resources.NotFoundException e) {
            description.setBackgroundColor(Color.LTGRAY);
            descriptionHtml = waypoint.description;
        }

        WebSettings settings = description.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowFileAccess(true);
        Uri baseUrl = Uri.fromFile(new File(application.dataPath));
        description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null);
    }

    String coords = StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude);
    ((TextView) view.findViewById(R.id.coordinates)).setText(coords);

    if (waypoint.altitude != Integer.MIN_VALUE) {
        ((TextView) view.findViewById(R.id.altitude)).setText(StringFormatter.elevationH(waypoint.altitude));
    }

    double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude);
    double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude);
    bearing = application.fixDeclination(bearing);
    String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing);
    ((TextView) view.findViewById(R.id.distance)).setText(distance);

    if (waypoint.date != null)
        ((TextView) view.findViewById(R.id.date))
                .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " "
                        + DateFormat.getTimeFormat(activity).format(waypoint.date));
    else
        ((TextView) view.findViewById(R.id.date)).setVisibility(View.GONE);

    dialog.setTitle(waypoint.name);
}

From source file:com.androzic.waypoint.WaypointDetails.java

@SuppressLint("NewApi")
private void updateWaypointDetails(double lat, double lon) {
    Androzic application = Androzic.getApplication();
    AppCompatActivity activity = (AppCompatActivity) getActivity();

    activity.getSupportActionBar().setTitle(waypoint.name);

    View view = getView();// w  ww .j a v  a2s.co m

    final TextView coordsView = (TextView) view.findViewById(R.id.coordinates);
    coordsView.requestFocus();
    coordsView.setTag(Integer.valueOf(StringFormatter.coordinateFormat));
    coordsView.setText(StringFormatter.coordinates(" ", waypoint.latitude, waypoint.longitude));
    coordsView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int format = ((Integer) coordsView.getTag()).intValue() + 1;
            if (format == 5)
                format = 0;
            coordsView.setText(StringFormatter.coordinates(format, " ", waypoint.latitude, waypoint.longitude));
            coordsView.setTag(Integer.valueOf(format));
        }
    });

    if (waypoint.altitude != Integer.MIN_VALUE) {
        ((TextView) view.findViewById(R.id.altitude))
                .setText("\u2336 " + StringFormatter.elevationH(waypoint.altitude));
        view.findViewById(R.id.altitude).setVisibility(View.VISIBLE);
    } else {
        view.findViewById(R.id.altitude).setVisibility(View.GONE);
    }

    if (waypoint.proximity > 0) {
        ((TextView) view.findViewById(R.id.proximity))
                .setText("~ " + StringFormatter.distanceH(waypoint.proximity));
        view.findViewById(R.id.proximity).setVisibility(View.VISIBLE);
    } else {
        view.findViewById(R.id.proximity).setVisibility(View.GONE);
    }

    double dist = Geo.distance(lat, lon, waypoint.latitude, waypoint.longitude);
    double bearing = Geo.bearing(lat, lon, waypoint.latitude, waypoint.longitude);
    bearing = application.fixDeclination(bearing);
    String distance = StringFormatter.distanceH(dist) + " " + StringFormatter.angleH(bearing);
    ((TextView) view.findViewById(R.id.distance)).setText(distance);

    ((TextView) view.findViewById(R.id.waypointset)).setText(waypoint.set.name);

    if (waypoint.date != null) {
        view.findViewById(R.id.date_row).setVisibility(View.VISIBLE);
        ((TextView) view.findViewById(R.id.date))
                .setText(DateFormat.getDateFormat(activity).format(waypoint.date) + " "
                        + DateFormat.getTimeFormat(activity).format(waypoint.date));
    } else {
        view.findViewById(R.id.date_row).setVisibility(View.GONE);
    }

    if ("".equals(waypoint.description)) {
        view.findViewById(R.id.description_row).setVisibility(View.GONE);
    } else {
        WebView description = (WebView) view.findViewById(R.id.description);
        String descriptionHtml;
        try {
            TypedValue tv = new TypedValue();
            Theme theme = activity.getTheme();
            Resources resources = getResources();
            theme.resolveAttribute(android.R.attr.textColorPrimary, tv, true);
            int secondaryColor = resources.getColor(tv.resourceId);
            String css = String.format(
                    "<style type=\"text/css\">html,body{margin:0;background:transparent} *{color:#%06X}</style>\n",
                    (secondaryColor & 0x00FFFFFF));
            descriptionHtml = css + waypoint.description;
            description.setWebViewClient(new WebViewClient() {
                @SuppressLint("NewApi")
                @Override
                public void onPageFinished(WebView view, String url) {
                    view.setBackgroundColor(Color.TRANSPARENT);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        view.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
                }
            });
            description.setBackgroundColor(Color.TRANSPARENT);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                description.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        } catch (Resources.NotFoundException e) {
            description.setBackgroundColor(Color.LTGRAY);
            descriptionHtml = waypoint.description;
        }

        WebSettings settings = description.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
        settings.setAllowFileAccess(true);
        Uri baseUrl = Uri.fromFile(new File(application.dataPath));
        description.loadDataWithBaseURL(baseUrl.toString() + "/", descriptionHtml, "text/html", "utf-8", null);
        view.findViewById(R.id.description_row).setVisibility(View.VISIBLE);
    }
}

From source file:org.botlibre.sdk.activity.ChatActivity.java

public void response(final ChatResponse response) {
    if (speechPlayer != null || tts != null) {
        try {//from  w ww .  j  a v  a  2 s.  c  o m
            tts.stop();
            speechPlayer.pause();
        } catch (Exception ignore) {
            Log.e("RESPONSE", "Error: " + ignore.getMessage());
        }
    }
    //needs when calling "sleep" or the its not going to let the mic off
    //also to stop the mic until the bot finish the sentence
    try {
        stopListening();
        this.response = response;

        String status = "";
        if (response.emote != null && !response.emote.equals("NONE")) {
            status = status + response.emote.toLowerCase();
        }
        if (response.action != null) {
            if (!status.isEmpty()) {
                status = status + " ";
            }
            status = status + response.action;
        }
        if (response.pose != null) {
            if (!status.isEmpty()) {
                status = status + " ";
            }
            status = status + response.pose;
        }

        if (response.command != null) {
            JSONObject jsonObject = response.getCommand();
            Command command = new Command(this, jsonObject);
        }

        TextView statusView = (TextView) findViewById(R.id.statusText);
        statusView.setText(status);

        final String text = response.message;
        final ListView list = (ListView) findViewById(R.id.chatList);
        if (text == null) {
            list.post(new Runnable() {
                @Override
                public void run() {
                    ChatResponse ready = new ChatResponse();
                    ready.message = "ready";
                    messages.add(ready);
                    ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                    list.invalidateViews();
                    if (list.getCount() > 2) {
                        list.setSelection(list.getCount() - 2);
                    }
                    beginListening();
                }
            });
            return;
        }
        list.post(new Runnable() {
            @Override
            public void run() {
                messages.add(response);
                ((ChatListAdapter) list.getAdapter()).notifyDataSetChanged();
                list.invalidateViews();
                if (list.getCount() > 2) {
                    list.setSelection(list.getCount() - 2);
                }
            }
        });

        WebView responseView = (WebView) findViewById(R.id.responseText);
        String html = Utils.linkHTML(text);
        if (html.contains("<") && html.contains(">")) {
            html = linkPostbacks(html);
        }
        responseView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);

        boolean talk = (text.trim().length() > 0) && (MainActivity.deviceVoice
                || (this.response.speech != null && this.response.speech.length() > 0));
        if (MainActivity.sound && talk) {
            if (!MainActivity.disableVideo && !videoError && this.response.isVideo()
                    && this.response.isVideoTalk()) {

                videoView.setOnPreparedListener(new OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        try {
                            mp.setLooping(true);
                            if (!MainActivity.deviceVoice) {
                                // Voice audio
                                speechPlayer = playAudio(response.speech, false, false, false);
                                speechPlayer.setOnCompletionListener(new OnCompletionListener() {
                                    @Override
                                    public void onCompletion(MediaPlayer mp) {
                                        mp.release();
                                        videoView.post(new Runnable() {
                                            public void run() {
                                                cycleVideo(response);
                                            }
                                        });
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                if (!music) {
                                                    beginListening();
                                                }
                                            }
                                        });
                                    }
                                });

                                speechPlayer.start();
                            } else {
                                HashMap<String, String> params = new HashMap<String, String>();
                                params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id");

                                tts.speak(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params);
                            }
                        } catch (Exception exception) {
                            Log.wtf(exception.getMessage(), exception);
                        }
                    }
                });
                playVideo(this.response.avatarTalk, false);
            } else if (talk) {
                if (!MainActivity.deviceVoice) {
                    // Voice audio
                    playAudio(this.response.speech, false, false, true);
                } else {
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "id");

                    this.tts.speak(Utils.stripTags(text), TextToSpeech.QUEUE_FLUSH, params);
                }
            }
        } else if (talk && (!MainActivity.disableVideo && !videoError && this.response.isVideo()
                && this.response.avatarTalk != null)) {
            videoView.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.setLooping(false);
                }
            });
            videoView.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    videoView.setOnCompletionListener(null);
                    cycleVideo(response);
                }
            });
            playVideo(this.response.avatarTalk, false);
            runOnUiThread(new Runnable() {
                public void run() {
                    beginListening();
                }
            });
        } else {
            runOnUiThread(new Runnable() {
                public void run() {
                    beginListening();
                }
            });
        }
    } catch (Exception exception) {
        Log.wtf(exception.getMessage(), exception);
    }
    if (micLastStat) {
        MainActivity.listenInBackground = true;
    }
}

From source file:net.healeys.lexic.online.OnlineGame.java

public boolean submitWords(WebView display) {
    Pattern contentPat = Pattern.compile("([^;]+); charset=(.+)");
    for (int attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
        String url = BASE_URL + urls.get("words");

        Iterator<String> li = uniqueListIterator();
        StringBuffer sb = new StringBuffer(4096);
        while (li.hasNext()) {
            sb.append(li.next());/*from w  ww  .j  av  a2s .  c  om*/
            if (li.hasNext())
                sb.append(',');
        }
        String data = URLEncoder.encode(sb.toString());

        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            addHeaders(post);

            post.setEntity(new StringEntity("words=" + data));

            HttpResponse resp = httpClient.execute(post);
            BufferedReader br = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            sb = new StringBuffer(4096);
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }

            String contentHeader = resp.getFirstHeader("Content-type").getValue();
            String contentType;
            String contentEncoding;
            Matcher mat = contentPat.matcher(contentHeader);
            if (mat.find()) {
                contentType = contentHeader.substring(mat.start(1), mat.end(1));
                contentEncoding = contentHeader.substring(mat.start(2), mat.end(2));
            } else {
                contentType = contentHeader;
                contentEncoding = "utf-8";
            }

            // Log.d(TAG,"url:"+url);
            // Log.d(TAG,"data:"+sb.toString());
            // Log.d(TAG,"contentType:"+contentType);
            // Log.d(TAG,"contentEncoding:"+contentEncoding);

            display.loadDataWithBaseURL(url, sb.toString(), "text/html", "utf-8", null);
            return true;
        } catch (Exception e) {
            // Log.d(TAG,"error submitting words",e);
        }
    }
    return false;
}

From source file:bolts.WebViewAppLinkResolver.java

@Override
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) {
    final Capture<String> content = new Capture<String>();
    final Capture<String> contentType = new Capture<String>();
    return Task.callInBackground(new Callable<Void>() {
        @Override//from  w  w  w.  j  a v a2 s  .  co  m
        public Void call() throws Exception {
            URL currentURL = new URL(url.toString());
            URLConnection connection = null;
            while (currentURL != null) {
                // Fetch the content at the given URL.
                connection = currentURL.openConnection();
                if (connection instanceof HttpURLConnection) {
                    // Unfortunately, this doesn't actually follow redirects if they go from http->https,
                    // so we have to do that manually.
                    ((HttpURLConnection) connection).setInstanceFollowRedirects(true);
                }
                connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX);
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) {
                        currentURL = new URL(httpConnection.getHeaderField("Location"));
                        httpConnection.disconnect();
                    } else {
                        currentURL = null;
                    }
                } else {
                    currentURL = null;
                }
            }

            try {
                content.set(readFromConnection(connection));
                contentType.set(connection.getContentType());
            } finally {
                if (connection instanceof HttpURLConnection) {
                    ((HttpURLConnection) connection).disconnect();
                }
            }
            return null;
        }
    }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() {
        @Override
        public Task<JSONArray> then(Task<Void> task) throws Exception {
            // Load the content in a WebView and use JavaScript to extract the meta tags.
            final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>();
            final WebView webView = new WebView(context);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setNetworkAvailable(false);
            webView.setWebViewClient(new WebViewClient() {
                private boolean loaded = false;

                private void runJavaScript(WebView view) {
                    if (!loaded) {
                        // After the first resource has been loaded (which will be the pre-populated data)
                        // run the JavaScript meta tag extraction script
                        loaded = true;
                        view.loadUrl(TAG_EXTRACTION_JAVASCRIPT);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    runJavaScript(view);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);
                    runJavaScript(view);
                }
            });
            // Inject an object that will receive the JSON for the extracted JavaScript tags
            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void setValue(String value) {
                    try {
                        tcs.trySetResult(new JSONArray(value));
                    } catch (JSONException e) {
                        tcs.trySetError(e);
                    }
                }
            }, "boltsWebViewAppLinkResolverResult");
            String inferredContentType = null;
            if (contentType.get() != null) {
                inferredContentType = contentType.get().split(";")[0];
            }
            webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null);
            return tcs.getTask();
        }
    }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() {
        @Override
        public AppLink then(Task<JSONArray> task) throws Exception {
            Map<String, Object> alData = parseAlData(task.getResult());
            AppLink appLink = makeAppLinkFromAlData(alData, url);
            return appLink;
        }
    });
}

From source file:com.farmerbb.notepad.activity.MainActivity.java

@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.KITKAT)/*  w w w.  ja v a  2  s.  co  m*/
public void printNote(String contentToPrint) {
    SharedPreferences pref = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);

    // Create a WebView object specifically for printing
    boolean generateHtml = !(pref.getBoolean("markdown", false)
            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
    WebView webView = generateHtml ? new WebView(this) : new MarkdownView(this);

    // Apply theme
    String theme = pref.getString("theme", "light-sans");
    int textSize = -1;

    String fontFamily = null;

    if (theme.contains("sans")) {
        fontFamily = "sans-serif";
    }

    if (theme.contains("serif")) {
        fontFamily = "serif";
    }

    if (theme.contains("monospace")) {
        fontFamily = "monospace";
    }

    switch (pref.getString("font_size", "normal")) {
    case "smallest":
        textSize = 12;
        break;
    case "small":
        textSize = 14;
        break;
    case "normal":
        textSize = 16;
        break;
    case "large":
        textSize = 18;
        break;
    case "largest":
        textSize = 20;
        break;
    }

    String topBottom = " " + Float.toString(getResources().getDimension(R.dimen.padding_top_bottom_print)
            / getResources().getDisplayMetrics().density) + "px";
    String leftRight = " " + Float.toString(getResources().getDimension(R.dimen.padding_left_right_print)
            / getResources().getDisplayMetrics().density) + "px";
    String fontSize = " " + Integer.toString(textSize) + "px";

    String css = "body { " + "margin:" + topBottom + topBottom + leftRight + leftRight + "; " + "font-family:"
            + fontFamily + "; " + "font-size:" + fontSize + "; " + "}";

    webView.getSettings().setJavaScriptEnabled(false);
    webView.getSettings().setLoadsImagesAutomatically(false);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(final WebView view, String url) {
            createWebPrintJob(view);
        }
    });

    // Load content into WebView
    if (generateHtml) {
        webView.loadDataWithBaseURL(null,
                "<link rel='stylesheet' type='text/css' href='data:text/css;base64,"
                        + Base64.encodeToString(css.getBytes(), Base64.DEFAULT) + "' /><html><body><p>"
                        + StringUtils.replace(contentToPrint, "\n", "<br>") + "</p></body></html>",
                "text/HTML", "UTF-8", null);
    } else
        ((MarkdownView) webView).loadMarkdown(contentToPrint,
                "data:text/css;base64," + Base64.encodeToString(css.getBytes(), Base64.DEFAULT));
}

From source file:com.sentaroh.android.TaskAutomation.Config.ActivityMain.java

@SuppressLint("NewApi")
final private void aboutTaskAutomation() {
    // common ??//  w w w  . j  av a2  s.  c o  m
    final Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.about_dialog);
    ((TextView) dialog.findViewById(R.id.about_dialog_title))
            .setText(getString(R.string.msgs_about_dlg_title) + " Ver " + getApplVersionName());
    final WebView func_view = (WebView) dialog.findViewById(R.id.about_dialog_function);
    //       func_view.setWebViewClient(new WebViewClient());
    //       func_view.getSettings().setJavaScriptEnabled(true); 
    func_view.getSettings().setSupportZoom(true);
    //      func_view.setVerticalScrollbarOverlay(true);
    func_view.setBackgroundColor(Color.LTGRAY);
    //      func_view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
    func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
    func_view.setVerticalScrollBarEnabled(true);
    func_view.setScrollbarFadingEnabled(false);
    if (Build.VERSION.SDK_INT > 10) {
        func_view.getSettings().setDisplayZoomControls(true);
        func_view.getSettings().setBuiltInZoomControls(true);
    } else {
        func_view.getSettings().setBuiltInZoomControls(true);
    }
    func_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_about_dlg_func_html));

    final WebView change_view = (WebView) dialog.findViewById(R.id.about_dialog_change_history);
    if (Build.VERSION.SDK_INT > 10) {
        func_view.getSettings().setDisplayZoomControls(true);
        func_view.getSettings().setBuiltInZoomControls(true);
    } else {
        func_view.getSettings().setBuiltInZoomControls(true);
    }
    change_view.loadDataWithBaseURL("file:///android_asset/", getString(R.string.msgs_about_dlg_change_desc),
            "text/html", "UTF-8", "");
    change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    change_view.getSettings().setSupportZoom(true);
    if (Build.VERSION.SDK_INT > 10) {
        change_view.getSettings().setDisplayZoomControls(true);
        change_view.getSettings().setBuiltInZoomControls(true);
    } else {
        change_view.getSettings().setBuiltInZoomControls(true);
    }

    final Button btnFunc = (Button) dialog.findViewById(R.id.about_dialog_btn_show_func);
    final Button btnChange = (Button) dialog.findViewById(R.id.about_dialog_btn_show_change);
    final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok);

    func_view.setVisibility(TextView.VISIBLE);
    change_view.setVisibility(TextView.GONE);
    btnChange.setBackgroundResource(R.drawable.button_back_ground_color_selector);
    btnFunc.setBackgroundResource(R.drawable.button_back_ground_color_selector);
    btnChange.setTextColor(Color.DKGRAY);
    btnFunc.setTextColor(Color.GREEN);
    btnFunc.setEnabled(false);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);

    // func?
    btnFunc.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            change_view.setVisibility(TextView.GONE);
            func_view.setVisibility(TextView.VISIBLE);
            CommonDialog.setDlgBoxSizeLimit(dialog, true);
            btnFunc.setTextColor(Color.GREEN);
            btnChange.setTextColor(Color.DKGRAY);
            btnChange.setEnabled(true);
            btnFunc.setEnabled(false);
        }
    });

    // change?
    btnChange.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            change_view.setVisibility(TextView.VISIBLE);
            func_view.setVisibility(TextView.GONE);
            CommonDialog.setDlgBoxSizeLimit(dialog, true);
            btnChange.setTextColor(Color.GREEN);
            btnFunc.setTextColor(Color.DKGRAY);
            btnChange.setEnabled(false);
            btnFunc.setEnabled(true);
        }
    });

    // OK?
    btnOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btnOk.performClick();
        }
    });
    //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
    //      dialog.setCancelable(false);
    dialog.show();

}