Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.hadoopz.MyDroidLib.webview.WebViewProcesser Maven / Gradle / Ivy
/*
* Copyright 2018 jw362j.
*
* 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.hadoopz.MyDroidLib.webview;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.*;
import android.webkit.*;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hadoopz.MyDroidLib.util.DefaultLogUtil;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient.CustomViewCallback;
/**
*
* @author jw362j
*/
public class WebViewProcesser extends Activity {
private TextView app_webViewTitle;
private TextView goBackTitle;
private WebView commWebView;
private ProgressDialog progress;
private static WebViewProcessListener processListener;
private String loadingUrl;
private String httpRequestData;
private static final String CHARSET = "UTF-8";
// private int titleLenght_Max = 40;
private boolean ssl_warning_flag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
initAndAddView();
}
private void initAndAddView() {
LinearLayout layout_root = new LinearLayout(WebViewProcesser.this);
LinearLayout.LayoutParams layout_rootParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.MATCH_PARENT);
layout_root.setOrientation(LinearLayout.VERTICAL);
//add title=====================================
RelativeLayout rl_title = new RelativeLayout(WebViewProcesser.this);
app_webViewTitle = new TextView(WebViewProcesser.this);
goBackTitle = new TextView(WebViewProcesser.this);
String theTitle = processListener.getBrowserTitle();
String browserTitle = theTitle == null ? "Back" : theTitle;
SpannableString msp_tv_back_text = new SpannableString(browserTitle);
msp_tv_back_text.setSpan(new RelativeSizeSpan(0.88f), 0, msp_tv_back_text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
goBackTitle.setText(msp_tv_back_text);
goBackTitle.setTextColor(Color.parseColor("#ffffff"));
app_webViewTitle.setTextColor(Color.parseColor("#ffffffff"));
rl_title.setBackgroundColor(Color.parseColor("#0577b2"));
app_webViewTitle.setPadding(0, 3, 0, 3);
app_webViewTitle.setText("");
RelativeLayout.LayoutParams rl_titleTextViewParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rl_titleTextViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
rl_titleTextViewParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
RelativeLayout.LayoutParams r2_titleTextViewParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
r2_titleTextViewParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
r2_titleTextViewParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
r2_titleTextViewParams.rightMargin = 10;
rl_title.addView(app_webViewTitle, rl_titleTextViewParams);
rl_title.addView(goBackTitle, r2_titleTextViewParams);
goBackTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//add title=====================================
//add webview=======================================
LinearLayout.LayoutParams commWebViewParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
commWebView = new WebView(WebViewProcesser.this);
//add webview=======================================
LinearLayout.LayoutParams rl_titleLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout_root.addView(rl_title, rl_titleLayoutParams);
layout_root.addView(commWebView, commWebViewParams);
setContentView(layout_root, layout_rootParams);
// ProgressDialog
progress = new ProgressDialog(WebViewProcesser.this);
progress.requestWindowFeature(Window.FEATURE_NO_TITLE);
progress.setMessage("Loading...");
progress.setCancelable(false);
progress.setCanceledOnTouchOutside(false);
if (processListener == null) {
Toast.makeText(WebViewProcesser.this, "url or postdata is null....", Toast.LENGTH_LONG).show();
finish();
return;
}
loadingUrl = processListener.getUrl();
StringBuilder sb_params = null;
Map ps = processListener.getParameters();
if (ps != null && !ps.isEmpty()) {
sb_params = new StringBuilder();
Set keys = ps.keySet();
for (String key : keys) {
try {
sb_params.append(URLEncoder.encode(key, CHARSET)).append("=").append(URLEncoder.encode(ps.get(key), CHARSET)).append("&");
} catch (UnsupportedEncodingException ex) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "the post data in UnsupportedEncodingException:" + ex.getMessage());
}
}
sb_params.deleteCharAt(sb_params.length() - 1);
DefaultLogUtil.getInstance().d("WebViewProcesser", "the post data in StringRequest is:" + sb_params.toString());
}
if (sb_params != null) {
httpRequestData = sb_params.toString().trim();
}
DefaultLogUtil.getInstance().d("WebViewProcesser", "detail for the request url:" + loadingUrl);
if ("".equals(loadingUrl) || loadingUrl == null) {
Toast.makeText(WebViewProcesser.this, "url is null....", Toast.LENGTH_LONG).show();
finish();
return;
}
//start to init the webview and load it
showDialog();
setUpWebView();
}
private void setUpWebView() {
WebSettings webSettings = commWebView.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setSaveFormData(false);
webSettings.setLightTouchEnabled(true);
webSettings.setSavePassword(false);
webSettings.setSupportZoom(false);
webSettings.setCacheMode(WebSettings.LOAD_NORMAL);
// webSettings.setMinimumFontSize(mMinimumFontSize);
// webSettings.setMinimumLogicalFontSize(mMinimumLogicalFontSize);
// webSettings.setDefaultFontSize(mDefaultFontSize);
// webSettings.setDefaultFixedFontSize(mDefaultFixedFontSize);
webSettings.setTextSize(WebSettings.TextSize.NORMAL);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setAllowFileAccess(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDefaultTextEncodingName(CHARSET);
webSettings.setDomStorageEnabled(true);//important line of code for html5 js script
commWebView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
if (i == KeyEvent.KEYCODE_BACK && commWebView.canGoBack()) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "webview goback");
if (commWebView.canGoBack()) {
commWebView.goBack();
} else {
WebViewProcesser.this.finish();
}
return true;
}
}
return false;
}
});
commWebView.setWebViewClient(new WebViewClient() {
/**
* in order to handle https request
*
* @param view
* @param handler
* @param error
* http://stackoverflow.com/questions/36050741/webview-avoid-security-alert-from-google-play-upon-implementation-of-onreceiveds
*/
@Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
if (!ssl_warning_flag) {
final AlertDialog.Builder builder = new AlertDialog.Builder(WebViewProcesser.this);
builder.setMessage("Invalid SSLCert From Server!");
builder.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
ssl_warning_flag = true;
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
} else {
handler.proceed();
}
DefaultLogUtil.getInstance().d("WebViewProcesser", "-test onReceivedSslError:" + error);
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return super.shouldInterceptRequest(view, url);
}
/**
* will be invoked once user click the link which in the page ,true
* :loading the page in this webview,false :go to system browser to
* load the page
*
* @param view
* @param url
* @return
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Uri uri = Uri.parse(url);
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);
} // else if(url.endsWith(".apk"))
else if (url.contains(".apk")) {
Uri uri = Uri.parse(url);
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
}
DefaultLogUtil.getInstance().d("WebViewProcesser", "shouldOverrideUrlLoading url:" + url);
if (!url.contains("about:blank") && url.contains("http")) {
view.loadUrl(url);
return true;
} else {
return false;
}
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
DefaultLogUtil.getInstance().d("WebViewProcesser", "-test onLoadResource url is:" + url);
}
/**
* will be invoked when the page is starting to load
*
* @param view
* @param url
* @param favicon
*/
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "-test onPageStarted url is:" + url);
DefaultLogUtil.getInstance().d("WebViewProcesser", "url length:" + url.length());
if ("about:blank".equals(url)) {
Toast.makeText(WebViewProcesser.this, "unrecognized url destination:" + url, Toast.LENGTH_LONG).show();
WebViewProcesser.this.finish();
// if(commWebView.canGoBack())commWebView.goBack();
return;
}
super.onPageStarted(view, url, favicon);
showDialog();
String return_url = processListener.getReturnUrl();
if (return_url != null) {
if (url.startsWith(return_url)) {
view.stopLoading();
if (processListener != null) {
finish();
processListener.onWebViewProcess(WebViewProcesser.this, url);
}
}
}
}
@Override
public void onPageFinished(WebView view, String url) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "-test onPageFinished:");
super.onPageFinished(view, url);
hideDialog();
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "webview error,errorCode:" + errorCode + ",description:" + description + ",failingUrl:" + failingUrl);
view.stopLoading();
hideDialog();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
commWebView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onConsoleMessage(ConsoleMessage cm) {
String consoleMsg = "javascript console message by tguard sdk:" + cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId();
DefaultLogUtil.getInstance().d("WebViewProcesser", consoleMsg);
return true;
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
DefaultLogUtil.getInstance().d("WebViewProcesser", "in MyChromeClient and newProgress is:" + newProgress);
}
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (!"".equals(title) && title != null) {
// app_webViewTitle.setText(title.length() > titleLenght_Max ? title.substring(0, titleLenght_Max - 5) + "..." : title);
}
}
@Override
public View getVideoLoadingProgressView() {
FrameLayout frameLayout = new FrameLayout(WebViewProcesser.this);
frameLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
return frameLayout;
}
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
showCustomView(view, callback);
}
@Override
public void onHideCustomView() {
hideCustomView();
}
});
if (processListener != null) {
processListener.setUpWebview(commWebView);
HttpRequestMethodType method = processListener.getRequestMethod();
if (method == HttpRequestMethodType.HTTP_GET) {
String target_url = httpRequestData == null ? loadingUrl : loadingUrl + "?" + httpRequestData;
DefaultLogUtil.getInstance().d("WebViewProcesser", "the request was send by get:" + target_url);
Map headers = processListener.getHttpHeaders();
DefaultLogUtil.getInstance().d("WebViewProcesser", "the header in webview:" + headers);
if (headers == null) {
commWebView.loadUrl(target_url);
} else {
DefaultLogUtil.getInstance().d("WebViewProcesser", "apply the header in webview request!");
commWebView.loadUrl(target_url, headers);
}
} else if (method == HttpRequestMethodType.HTTP_POST) {
DefaultLogUtil.getInstance().d("WebViewProcesser", "the request was send by post , post data is:" + httpRequestData + ",url is:" + loadingUrl);
try {
commWebView.postUrl(loadingUrl, httpRequestData.getBytes(CHARSET));
} catch (UnsupportedEncodingException ex) {
DefaultLogUtil.getInstance().d("WebViewProcesser", ex.getMessage());
}
}
}
}
public static void startMe(Context context, WebViewProcessListener webViewProcessListener) {
if (webViewProcessListener == null) {
DefaultLogUtil.getInstance().e("WebViewProcesser", "webViewProcessListener is null ,could not start web-flow as well ,just stop.............");
return;
}
processListener = webViewProcessListener;//when the process ready,then let the listener null
if (context != null) {
context.startActivity(new Intent(context, WebViewProcesser.class));
} else {
DefaultLogUtil.getInstance().d("WebViewProcesser", "context is null ,could not start web-flow as well ,just stop.............");
}
}
private void showDialog() {
if (progress != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!progress.isShowing()) {
progress.show();
}
}
});
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (commWebView.canGoBack()) {
commWebView.goBack();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
private void hideDialog() {
if (progress != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress.dismiss();
}
});
}
}
@Override
public void onLowMemory() {
commWebView.clearCache(true);
super.onLowMemory();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (progress != null) {
progress = null;
}
if (commWebView != null) {
commWebView.clearCache(true);
commWebView.clearFormData();
commWebView.removeAllViews();
commWebView = null;
}
loadingUrl = null;
httpRequestData = null;
}
private FullscreenHolder fullscreenContainer;
private View customView;
private WebChromeClient.CustomViewCallback customViewCallback;
protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
/**
* 视频播放全屏 *
*/
private void showCustomView(View view, CustomViewCallback callback) {
// if a view already exists then immediately terminate the new one
if (customView != null) {
callback.onCustomViewHidden();
return;
}
WebViewProcesser.this.getWindow().getDecorView();
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
fullscreenContainer = new FullscreenHolder(WebViewProcesser.this);
fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
customView = view;
setStatusBarVisibility(false);
customViewCallback = callback;
}
/**
* 隐藏视频全屏
*/
private void hideCustomView() {
if (customView == null) {
return;
}
setStatusBarVisibility(true);
FrameLayout decor = (FrameLayout) getWindow().getDecorView();
decor.removeView(fullscreenContainer);
fullscreenContainer = null;
customView = null;
customViewCallback.onCustomViewHidden();
commWebView.setVisibility(View.VISIBLE);
}
/**
* 全屏容器界面
*/
static class FullscreenHolder extends FrameLayout {
public FullscreenHolder(Context ctx) {
super(ctx);
setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
}
@Override
public boolean onTouchEvent(MotionEvent evt) {
return true;
}
}
private void setStatusBarVisibility(boolean visible) {
int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
/**
* 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面
*/
if (customView != null) {
hideCustomView();
} else if (commWebView.canGoBack()) {
commWebView.goBack();
} else {
finish();
}
return true;
default:
return super.onKeyUp(keyCode, event);
}
}
}