下面列出了android.webkit.WebView#loadDataWithBaseURL ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void loadCodeAtWebView(Context context, String code, WebView webView) {
webView.getSettings().setJavaScriptEnabled(true);
InputStream inputStream = null;
String template = null;
try {
inputStream = context.getAssets().open("index.html");
template = readTextFile(inputStream);
template = template.replace("__CODE__", Html.escapeHtml(code));
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(inputStream);
}
String baseUrl = "file:///android_asset/";
webView.loadDataWithBaseURL(baseUrl, template, "text/html", "UTF-8", "");
}
public void viewGoogleLicenses(View myview) {
try {
if (!appended) {
final String googleLicense = GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(getApplicationContext());
if (googleLicense != null) {
String whiteheader = "<font size=-2 color=white><pre>";
String whitefooter = "</font></pre>";
WebView textview = (WebView) findViewById(R.id.webView);
textview.setBackgroundColor(Color.TRANSPARENT);
textview.getSettings().setJavaScriptEnabled(false);
textview.loadDataWithBaseURL("", whiteheader + googleLicense + whitefooter, "text/html", "UTF-8", "");
appended = true;
findViewById(R.id.googlelicenses).setVisibility(View.INVISIBLE);
findViewById(R.id.webView).setVisibility(View.VISIBLE);
} else {
UserError.Log.d(TAG, "Nullpointer getting Google License: errorcode:" + GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(getApplicationContext()));
findViewById(R.id.googlelicenses).setVisibility(View.INVISIBLE);
}
}
} catch (Exception e) {
// meh
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
getSupportActionBar().setTitle(getString(R.string.about));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressBar = (ProgressBar) findViewById(R.id.progress);
progressBar.getIndeterminateDrawable()
.setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), PorterDuff.Mode.SRC_IN);
info_web = (WebView) findViewById(R.id.webview_company_info);
info_web.setBackgroundColor(Color.TRANSPARENT);
info_web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
info_web.setWebViewClient(new myWebClient());
info_web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
info_web.getSettings().setJavaScriptEnabled(true);
String infoText = getString(R.string.company_info_web);
info_web.loadDataWithBaseURL("file:///android_asset/fonts/", getWebViewText(infoText), "text/html", "utf-8", null);
}
public void resetChat(View view) {
ChatConfig config = new ChatConfig();
config.instance = instance.id;
config.avatar = this.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.speak = !MainActivity.deviceVoice;
HttpAction action = new HttpChatAction(ChatActivity.this, config);
action.execute();
EditText v = (EditText) findViewById(R.id.messageText);
v.setText("");
this.messages.clear();
runOnUiThread(new Runnable(){
@Override
public void run() {
ListView list = (ListView) findViewById(R.id.chatList);
((ChatListAdapter)list.getAdapter()).notifyDataSetChanged();
list.invalidateViews();
}
});
WebView responseView = (WebView) findViewById(R.id.responseText);
responseView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
}
public static void loadContentAdaptiveScreen(Context mContext,
WebView webview, String content) {
final String mimeType = "text/html";
final String encoding = "UTF-8";
webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webview.loadDataWithBaseURL("", content, mimeType, encoding, "");
}
public void submitChat(String message) {
if (this.finished) {
return;
}
ChatConfig config = new ChatConfig();
config.instance = this.instance.id;
config.conversation = MainActivity.conversation;
config.speak = !MainActivity.deviceVoice;
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 = message;
runOnUiThread(new Runnable(){
@Override
public void run() {
ListView list = (ListView) findViewById(R.id.chatList);
((ChatListAdapter)list.getAdapter()).notifyDataSetChanged();
list.invalidateViews();
}
});
HttpChatAction action = new HttpChatAction(WarActivity.this, config);
action.execute();
HttpGetImageAction.fetchImage(this, this.instance.avatar, findViewById(R.id.responseImageView));
WebView responseView = (WebView) findViewById(R.id.responseText);
responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_info, container, false);
String webViewHtml = getArguments().getString(WEBVIEW_HTML);
mWebView = (WebView) v.findViewById(R.id.infoActivityWV);
mWebView.loadDataWithBaseURL(null, webViewHtml, "text/html", "utf-8", null);
return v;
}
@Override
public void showLicense(License license) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_licence_detail_workflow, null);
dialogBuilder.setView(dialogView);
TextView title = dialogView.findViewById(R.id.tvDialogTitle);
TextView date = dialogView.findViewById(R.id.tvDialogDate);
WebView text = dialogView.findViewById(R.id.wvDialogText);
Button buttonOk = dialogView.findViewById(R.id.bDialogOK);
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
text.loadDataWithBaseURL("", license.getDescription(), "text/html", "utf-8", "");
date.setText(license.getCreatedAt().substring(0, license.getCreatedAt().indexOf(' ')));
title.setText(license.getTitle());
alertDialog = dialogBuilder.create();
alertDialog.show();
}
@Override
public void showAnnouncementDetail(DetailAnnouncement detailAnnouncement) {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
mAnnouncementDetail = detailAnnouncement;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.detail_annoucement_dialog_layout, null);
dialogBuilder.setView(dialogView);
TextView title = dialogView.findViewById(R.id.tvDialogTitle);
TextView date = dialogView.findViewById(R.id.tvDialogDate);
TextView author = dialogView.findViewById(R.id.tvDialogAuthor);
WebView text = dialogView.findViewById(R.id.wvDialogText);
Button buttonOk = dialogView.findViewById(R.id.bDialogOK);
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
text.loadDataWithBaseURL("", mAnnouncementDetail.getText(), "text/html", "utf-8", "");
date.setText(mAnnouncementDetail.getDate());
title.setText(mAnnouncementDetail.getTitle());
author.setText(mAnnouncementDetail.getAuthor().getContent());
alertDialog = dialogBuilder.create();
alertDialog.show();
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
String errorHtml= "<html><body><h1>网络异常,请检查网络后重试</h1></body></html>";
Logs.i("-MyWebViewClient->onReceivedError()--\n errorCode=" + errorCode + " \ndescription=" + description + " \nfailingUrl=" + failingUrl);
//这里进行无网络或错误处理,具体可以根据errorCode的值进行判断,做跟详细的处理。
// view.loadData("<html><body><h1>"+"网络异常,请检查网络后重试"+"</h1></body></html>", "text/html", "gbk");
view.loadDataWithBaseURL("","<html><body><h1>"+"网络异常,请检查网络后重试"+"</h1></body></html>", "text/html", "utf-8", null);
}
public void submitChat() {
ChatConfig config = new ChatConfig();
config.instance = this.instance.id;
config.conversation = MainActivity.conversation;
config.speak = !MainActivity.deviceVoice;
config.avatar = this.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;
EditText v = (EditText) findViewById(R.id.messageText);
config.message = v.getText().toString().trim();
if (config.message.equals("")) {
return;
}
this.messages.add(config);
runOnUiThread(new Runnable(){
@Override
public void run() {
ListView list = (ListView) findViewById(R.id.chatList);
((ChatListAdapter)list.getAdapter()).notifyDataSetChanged();
list.invalidateViews();
}
});
//Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin);
//config.emote = emoteSpin.getSelectedItem().toString();
HttpChatAction action = new HttpChatAction(ChatActivity.this, config);
action.execute();
v.setText("");
//emoteSpin.setSelection(0);
resetToolbar();
WebView responseView = (WebView) findViewById(R.id.responseText);
responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);
//Check the volume
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
if (volume <= 1 && volumeChecked) {
Toast.makeText(this, "Please check 'Media' volume", Toast.LENGTH_LONG).show();
volumeChecked = false;
}
//stop letting the mic on.
stopListening();
//its Important for "sleep" "scream" ...etc commands.
//this will turn off the mic
MainActivity.listenInBackground = false;
}
/**
* Clear the log.
*/
public void clear(View view) {
WebView log = (WebView) findViewById(R.id.logText);
log.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
}
public void clearLog() {
this.html = "";
WebView log = (WebView) findViewById(R.id.logText);
log.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
}
@ReactProp(name = "source")
public void setSource(WebView view, @NonNull ReadableMap source) {
if (source != null) {
if (source.hasKey("html")) {
String html = source.getString("html");
if (source.hasKey("baseUrl")) {
view.loadDataWithBaseURL(
source.getString("baseUrl"), html, HTML_MIME_TYPE, HTML_ENCODING, null);
} else {
view.loadData(html, HTML_MIME_TYPE, HTML_ENCODING);
}
return;
}
if (source.hasKey("uri")) {
String url = source.getString("uri");
String previousUrl = view.getUrl();
if (source.hasKey("method")) {
String method = source.getString("method");
if (method.equals(HTTP_METHOD_POST)) {
byte[] postData = null;
if (source.hasKey("body")) {
String body = source.getString("body");
try {
postData = body.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
postData = body.getBytes();
}
}
if (postData == null) {
postData = new byte[0];
}
view.postUrl(url, postData);
return;
}
}
HashMap<String, String> headerMap = new HashMap<>();
if (source.hasKey("headers")) {
ReadableMap headers = source.getMap("headers");
ReadableMapKeySetIterator iter = headers.keySetIterator();
while (iter.hasNextKey()) {
String key = iter.nextKey();
if ("user-agent".equals(key.toLowerCase(Locale.ENGLISH))) {
if (view.getSettings() != null) {
view.getSettings().setUserAgentString(headers.getString(key));
}
} else {
headerMap.put(key, headers.getString(key));
}
}
}
view.loadUrl(url, headerMap);
return;
}
}
view.loadUrl(BLANK_URL);
}
public void response(String text) {
if (this.closing) {
return;
}
String user = "";
String message = text;
int index = text.indexOf(':');
if (index != -1) {
user = text.substring(0, index);
message = text.substring(index + 2, text.length());
}
if (user.equals("Online")) {
HttpAction action = new HttpGetLiveChatUsersAction(this, message);
action.execute();
return;
}
if (user.equals("Media")) {
return;
}
if (user.equals("Channel")) {
return;
}
WebView log = (WebView) findViewById(R.id.logText);
message = Utils.linkHTML(message);
if (message.contains("<") && message.contains(">")) {
message = linkPostbacks(message);
}
this.html = this.html + "<b>" + user + "</b> <span style='font-size:10px;color:grey'>"
+ Utils.displayTime(new Date()) + "</span><br/>"
+ Utils.linkHTML(message) + "<br/>";
log.loadDataWithBaseURL(null, this.html, "text/html", "utf-8", null);
final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView);
scroll.postDelayed(new Runnable() {
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
}, 200);
scroll.postDelayed(new Runnable() {
public void run() {
scroll.fullScroll(View.FOCUS_DOWN);
}
}, 400);
if ((System.currentTimeMillis() - startTime) < (1000 * 5)) {
return;
}
boolean speak = this.speak;
boolean chime = this.chime;
if (user.equals("Error") || user.equals("Info")) {
speak = false;
} else if (MainActivity.user == null) {
if (user.startsWith("anonymous")) {
speak = false;
chime = false;
}
} else {
if (user.equals(MainActivity.user.user)) {
speak = false;
chime = false;
}
}
if (speak) {
this.tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
} else if (chime) {
if (this.chimePlayer != null && this.chimePlayer.isPlaying()) {
return;
}
chime();
}
}
public void submitChat() {
ChatConfig config = new ChatConfig();
config.instance = this.instance.id;
config.conversation = MainActivity.conversation;
config.speak = !MainActivity.deviceVoice;
config.avatar = this.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;
EditText v = (EditText) findViewById(R.id.messageText);
config.message = v.getText().toString().trim();
if (config.message.equals("")) {
return;
}
this.messages.add(config);
ListView list = (ListView) findViewById(R.id.chatList);
//add list to the list
list.addItem("You: "+config.message);
list.invalidateViews();
Spinner emoteSpin = (Spinner) findViewById(R.id.emoteSpin);
config.emote = emoteSpin.getSelectedItem().toString();
HttpChatAction action = new HttpChatAction(ChatActivity.this, config);
action.execute();
v.setText("");
emoteSpin.setSelection(0);
resetToolbar();
WebView responseView = (WebView) findViewById(R.id.responseText);
responseView.loadDataWithBaseURL(null, "thinking...", "text/html", "utf-8", null);
}
@SuppressLint("SetJavaScriptEnabled")
@TargetApi(Build.VERSION_CODES.KITKAT)
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));
}
public static void loadDataWithCss(WebView webView, String html, String cssPath){
String css = !TextUtils.isEmpty(cssPath)? String.format(CSS_LINK_PLACE_HOLDER, cssPath): "";
webView.loadDataWithBaseURL(null, css + html, "text/html", "UTF-8", null);
}
private void showAboutDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.about_label);
String str = null;
try {
InputStream inputStream = getResources().getAssets().open(getString(R.string.about_readme));
str = IOUtils.toString(inputStream);
} catch (IOException i) {
/* Do nothing */
}
final WebView webView = new WebView(MainActivity.this);
webView.loadDataWithBaseURL(
StyleMarkdown.BASE_URL,
str,
null,
getString(R.string.webview_encoding),
null
);
webView.setVisibility(View.VISIBLE);
builder.setView(webView);
builder.setPositiveButton(R.string.about_button_star, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new Thread(starThread).start();
SuperToast.create(
MainActivity.this,
getString(R.string.about_thx),
SuperToast.Duration.VERY_SHORT,
Style.getStyle(Style.GREEN)
).show();
}
});
builder.setNegativeButton(R.string.about_button_close, null);
builder.setInverseBackgroundForced(true);
builder.setCancelable(false);
builder.create();
builder.show();
}
public boolean loadToWebView(WebView v) {
myWebView = v;
v.setWebViewClient(new WebClient());
WebSettings webSettings = v.getSettings();
webSettings.setDefaultTextEncodingName("UTF-8");
myLoadingArchive = true;
try {
// Find the first ArchiveResource in myDoc, should be <ArchiveResource>
Element ar = (Element) myDoc.getDocumentElement().getFirstChild().getFirstChild();
byte b[] = getElBytes(ar, "data");
// Find out the web page charset encoding
String charset = null;
String topHtml = new String(b).toLowerCase();
int n1 = topHtml.indexOf("<meta http-equiv=\"content-type\"");
if (n1 > -1) {
int n2 = topHtml.indexOf('>', n1);
if (n2 > -1) {
String tag = topHtml.substring(n1, n2);
n1 = tag.indexOf("charset");
if (n1 > -1) {
tag = tag.substring(n1);
n1 = tag.indexOf('=');
if (n1 > -1) {
tag = tag.substring(n1 + 1);
tag = tag.trim();
n1 = tag.indexOf('\"');
if (n1 < 0)
n1 = tag.indexOf('\'');
if (n1 > -1) {
charset = tag.substring(0, n1).trim();
}
}
}
}
}
if (charset != null)
topHtml = new String(b, charset);
else {
topHtml = new String(b);
/*
* CharsetMatch match = new CharsetDetector().setText(b).detect();
* if (match != null)
* try {
* Lt.d("Guessed enc: " + match.getName() + " conf: " + match.getConfidence());
* topHtml = new String(b, match.getName());
* } catch (UnsupportedEncodingException ue) {
* topHtml = new String(b);
* }
*/
}
String baseUrl = new String(getElBytes(ar, "url"));
v.loadDataWithBaseURL(baseUrl, topHtml, "text/html", "UTF-8", null);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}